如何解决这个奇怪的UnboundLocalError并实现一个良好的工作修补功能?

时间:2015-07-27 11:08:31

标签: python python-2.7 monkeypatching

我决定将补丁装饰器写成猴子补丁。我认为这很容易但是这段代码在运行时总会出现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一样可以访问,我不知道为什么会出现错误。

1 个答案:

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