This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Python function decorator scope losing variable
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: V.E.O, r.david.murray
Priority: normal Keywords:

Created on 2012-08-29 16:08 by V.E.O, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg169389 - (view) Author: V.E.O (V.E.O) Date: 2012-08-29 16:08
I just learned python @ decorator, it's cool, but soon I found my modified code coming out weird problems.

def with_wrapper(param1):
    def dummy_wrapper(fn):
        print param1
        param1 = 'new'
        fn(param1)
    return dummy_wrapper

def dummy():
    @with_wrapper('param1')
    def implementation(param2):
        print param2

dummy()



I debug it, it throws out exception at print param1

UnboundLocalError: local variable 'param1' referenced before assignment

If I remove param1 = 'new' this line, without any modify operation(link to new object) on variables from outer scope, this routine might working.

Is it meaning I only have made one copy of outer scope variables, then make modification?
The policy of variable scope towards decorator is different?
msg169390 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2012-08-29 16:11
When you assign a value to param1 it becomes a local variable, thus the error.  You should ask for help on your scoping questions from the python-tutor list or the general python-list.
History
Date User Action Args
2022-04-11 14:57:35adminsetgithub: 60017
2012-08-29 16:11:32r.david.murraysetstatus: open -> closed

type: compile error -> behavior

nosy: + r.david.murray
messages: + msg169390
resolution: not a bug
stage: resolved
2012-08-29 16:08:49V.E.Ocreate