python - How to fix this strange UnboundLocalError and implement a well working patching function? -


i determined write patch decorator monkey patch. thought easy code rises unboundlocalerror while running. source code here:

def patch(source, target):     def _(func):         def __():             print source        # `source` accessible expected             _target = target    # error here             target = source             func()             target = _target         return __     return _   import os  @patch(patch, os) def f():     pass  f() 

full traceback:

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 

the variable target should accessible variable source, have not idea why rise error.

i hope want:

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

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -