0

insert や select などの一般的な関数をラップするヘルパー関数を多数作成しました。以下に含まれているのは、それらのラッパーの 1 つにすぎません...なぜ機能しないのかわかりません。

ラッパーと関係があると思われます:

from collections import Mapping
import sqlite3

def counter(func):
    def wrapper(*args, **kwargs):
        wrapper.count = wrapper.count + 1
    wrapper.count = 0
    return wrapper

@counter
def insert(val, cursor, table="reuters_word_list", logfile="queries.log"):
    if val:
        if isinstance(val, (basestring, Mapping)):
            val='\"'+val+'\"'
        query = ("insert into %s values (?);" % 'tablename', val)
        if logfile:
            to_logfile(query + '\n', logfile)
        cursor.execute(query)

if __name__ == '__main__':
    connection = sqlite3.connect('andthensome.db')
    cursor = connection.cursor()
    cursor.execute("create table wordlist (word text);")
    insert("foo", cursor)
    connection.commit()
    cursor.execute("select * from wordlist;")
    print cursor.fetchall()
    cursor.close()
4

1 に答える 1

6

カウンター デコレータが実際にfun を呼び出すことはありません。

試す

def counter(func):
    def wrapper(*args, **kwargs):
        wrapper.count += 1
        return func(*args, **kwargs)       # <- this line is important!!
    wrapper.count = 0
    return wrapper
于 2012-06-10T03:06:13.407 に答える