包装纯函数(非方法)

有没有办法在Python中包装函数调用?
我试过以下几种方法:

选择 | 换行 | 行号
  1. def wrap(f, wrapper):
  2.  
  3.     def h(*args, **opts):  pass
  4.     h.func_code = f.func_code
  5.  
  6.     def w(*args, **opts):
  7.         wrapper(args, opts)
  8.         return h(args, opts)
  9.  
  10.     f.func_code = w.func_code
  11.     return w
  12.  
  13.  
  14. def test_f():
  15.     print 'test_f()'
  16.  
  17. def test_wrapper(*args):
  18.     print 'test_wrapper()'
  19.  
  20. wrap(test_f, test_wrapper)
  21.  

但它不起作用,因为赋值"f.func_code=w.func_code"要求代码对象包含相同的空闲变量集(确切地说,错误消息是"
ValueError:test_f()需要一个具有0个自由变量的代码对象,而不是2个
"对于调用包装(test_f,test_wrapper))

# 回答1

选择 | 换行 | 行号
  1. wrap(test_f, test_wrapper)

上面代码中的test_f和test_wrapper是字符串,而不是函数()。您可以使用如下内容,但这可能不是您要尝试做的事情,因为我们不知道您想要做什么。

选择 | 换行 | 行号
  1. def wrap(f):
  2.      print "f()", f()
  3.  
  4. def test_f():
  5.      print 'test_f() called'
  6.  
  7. wrap(test_f) 

我建议你用字典,把字典递给你

选择 | 换行 | 行号
  1. def wrap():
  2.     print "wrap called"
  3.  
  4. def test_f():
  5.     print 'test_f() called'
  6.  
  7. def run_it(input_dict, name_to_run):
  8.     input_dict[name_to_run]()
  9.  
  10. wrap_dict={"test_f":test_f, "wrap":wrap}
  11. run_it(wrap_dict, "wrap") 

标签: python

添加新评论