Python wrapper preventing function call?

梦想的初衷 提交于 2019-12-25 04:59:18

问题


I've written a bunch of helper functions to wrap common functions such as insert and select. Included below is just one of those wrappers... which I can't seem to figure out why it isn't working.

I suspect it is something to do with the wrapper:

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()

回答1:


Your counter decorator never actually calls func.

Try

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


来源:https://stackoverflow.com/questions/10966104/python-wrapper-preventing-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!