Issue 12023: non causal behavior (original) (raw)

Created on 2011-05-06 22:53 by Rodrigo.Ventura, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (5)
msg135380 - (view) Author: Rodrigo Ventura (Rodrigo.Ventura) Date: 2011-05-06 22:53
Consider these two functions: --- def nok(): a = None def f(): if a: a = 1 f() def ok(): a = None def f(): if a: b = 1 f() --- Function ok() executes fine, but function nok() trigger an exception: Traceback (most recent call last): File "pb.py", line 20, in nok() File "pb.py", line 7, in nok f() File "pb.py", line 5, in f if a: UnboundLocalError: local variable 'a' referenced before assignment There is no reason for this to happen Regards, Rodrigo Ventura
msg135381 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2011-05-06 22:57
The reason is that in nok Python sees the assignment to a (a = 1) and determines that the 'a' variable is local to the scope of f, and since the assignment comes after the "if a:" and at that point 'a' has no value, an error is raised. In ok there's no assignment to 'a', so Python assume that 'a' refers to the 'a' variable defined in the outer scope.
msg135382 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2011-05-06 22:58
See also http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
msg135400 - (view) Author: Rodrigo Ventura (Rodrigo.Ventura) Date: 2011-05-07 03:21
Ezio, thank you for the explanation. Is it possible to access variable a in nok's scope from function f without using the global keyword in f? (so that variable a remains local to nok, rather than global to python) Rodrigo
msg135451 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2011-05-07 12:14
In 3.x, yes (the nonlocal keyword). Not in 2.7, though.
History
Date User Action Args
2022-04-11 14:57:17 admin set github: 56232
2011-05-07 12:14:50 r.david.murray set nosy: + r.david.murraymessages: +
2011-05-07 03:21:34 Rodrigo.Ventura set messages: +
2011-05-06 22:58:35 ezio.melotti set messages: +
2011-05-06 22:57:14 ezio.melotti set status: open -> closednosy: + ezio.melottimessages: + resolution: not a bugstage: resolved
2011-05-06 22:53:04 Rodrigo.Ventura create