包装纯函数(非方法)
有没有办法在Python中包装函数调用?
我试过以下几种方法:
选择 | 换行 | 行号
- def wrap(f, wrapper):
- def h(*args, **opts): pass
- h.func_code = f.func_code
- def w(*args, **opts):
- wrapper(args, opts)
- return h(args, opts)
- f.func_code = w.func_code
- return w
- def test_f():
- print 'test_f()'
- def test_wrapper(*args):
- print 'test_wrapper()'
- wrap(test_f, test_wrapper)
但它不起作用,因为赋值"f.func_code=w.func_code"要求代码对象包含相同的空闲变量集(确切地说,错误消息是"
ValueError:test_f()需要一个具有0个自由变量的代码对象,而不是2个
"对于调用包装(test_f,test_wrapper))