我决定将补丁装饰器写成猴子补丁。我认为这很容易但是这段代码在运行时总会出现UnboundLocalError。源代码在这里:
def patch(source, target):
def _(func):
def __():
print source # `source` is accessible as I expected
_target = target # Error here
target = source
func()
target = _target
return __
return _
import os
@patch(patch, os)
def f():
pass
f()
完整追溯:
Traceback (most recent call last):
File "test.py", line 18, in <module>
f()
File "test.py", line 4, in __
_target = target
UnboundLocalError: local variable 'target' referenced before assignment
变量target
也应该像变量source
一样可以访问,我不知道为什么会出现错误。
答案 0 :(得分:0)
我希望它能完全符合您的要求:
def patch(source, target):
t = target
def _(func):
def __():
print source
_target = t
target = source
func()
target = _target
return __
return _
import os
@patch(other_patch, os)
def f():
pass
f()