Repository navigation
UnboundLocalError in nested function #53295
Description
Activity
AndreasHofmeister commented
on Jun 21, 2010 AndreasHofmeistermannequinMannequinAuthorMore actionsDescription:
An unexpected UnboundLocalError is produced when assigning a value to a variable inside a nested function. The first assignment to the variable is in the enclosing function.Example:
def x():
a = False
def y():
print a
a = True
return yCalling x()() produces an UnboundLocalError on the 'print a' line.
If the 'a = True' line is removed, no error occurs.Tested with:
- 2.5.1
- 2.6.5
Keywords:
Nested function, UnboundLocalError, variable assignmentThank you for your attention
- addedinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Jun 21, 2010 This isn't a bug; it's by design.
Because there's an assignment to 'a' in the function 'y', 'a' is considered local to that function. (It doesn't matter where the assignment happens within the function; the presence of an assignment anywhere is enough to make 'a' local for the entirety of 'y'.)
This is described in the reference manual at:
http://docs.python.org/reference/executionmodel.html#naming-and-binding
See the paragraph beginning:
"If a name binding operation occurs anywhere within a code block, "
AndreasHofmeister commented
on Jun 22, 2010 AndreasHofmeistermannequinMannequinAuthorMore actionsThank you for your assistance. I apologize for not examining the reference manual closely.
Is there any way to produce the desired behavior? I currently work around the local name binding like this:def x(): a = [False] def y(): print a[0] a[0] = True return y
However, using a list here seems awkward.
Thank you for your attention.Is there any way to produce the desired behavior?
Not directly, in Python 2.x. (But there's the 'nonlocal' keyword in 3.x.) There are various workarounds, but what's best depends on what you're doing. The python-list mailing list is probably a better place to get answers.
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields: