Python包装器阻止函数调用?

use*_*003 0 python sqlite cursor wrapper

我编写了一堆辅助函数来包装常用函数,如insert和select.下面包含的只是其中一个包装器...我似乎无法弄清楚它为什么不起作用.

我怀疑它与包装器有关:

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()
Run Code Online (Sandbox Code Playgroud)

Hug*_*ell 6

您的计数器装饰器从未实际调用 func.

尝试

def counter(func):
    def wrapper(*args, **kwargs):
        wrapper.count += 1
        return func(*args, **kwargs)       # <- this line is important!!
    wrapper.count = 0
    return wrapper
Run Code Online (Sandbox Code Playgroud)