我一直致力于将 n 维数组序列化为一维“数组”数据库:
from collections import Iterable, Mapping
import sqlite3
def pass_many(vals, some_funct, args=()):
if not vals:
return
if isinstance(vals, Iterable) and not isinstance(vals, (basestring, Mapping)):
for v in vals:
pass_many(v, some_funct, args)
else:
some_funct(vals, *args)
def counter(func):
def wrapper(v, *args, **kwargs): # added 'v' arg to no avail
wrapper.count = wrapper.count + 1
test_var_args(v, *args, **kwargs)
#return func(*args, **kwargs)
wrapper.count = 0
return wrapper
def test_var_args(farg, *args):
print "formal arg:", farg
for arg in args:
print "another arg:", arg
@counter
def insert(val, cursor, table="wordlist", logfile="queries.log"):
print val, cursor, table, logfile
if val:
if isinstance(val, (basestring, Mapping)):
val = '\"' + val + '\"'
else: val = str(val)
query = "insert into tablename values (?);".replace('tablename', table).replace('?', 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 array (word text);")
pass_many([["foo", "bar"], "pew"], insert, cursor)
connection.commit()
cursor.execute("select * from array;") # wrapped select function omitted for brevity
print "insert() was called", insert.count, "times, and db now contains:\n", cursor.fetchall()
cursor.close()
输出:
formal arg: foo
formal arg: bar
formal arg: pew
insert() was called 3 times, and db now contains:
[]
输出取消注释#return func(*args, **kwargs)
:
formal arg: foo
Traceback (most recent call last):
Line 42, in <module>
pass_many([["foo", "bar"], "pew"], insert, cursor)
Line 9, in pass_many
pass_many(v, some_funct, args)
Line 9, in pass_many
pass_many(v, some_funct, args)
Line 11, in pass_many
some_funct(vals, *args)
Line 17, in wrapper
return func(*args, **kwargs)
TypeError: insert() takes at least 2 arguments (0 given)
预期输出(省略调试功能):
insert() was called 3 times, and db now contains:
["foo","bar","pew"]
insert
不幸的是,用装饰的函数似乎没有counter
正确传递参数。
我究竟做错了什么?