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: non causal behavior
Type: behavior Stage: resolved
Components: Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Rodrigo.Ventura, ezio.melotti, r.david.murray
Priority: normal Keywords:

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 <module>
    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:17adminsetgithub: 56232
2011-05-07 12:14:50r.david.murraysetnosy: + r.david.murray
messages: + msg135451
2011-05-07 03:21:34Rodrigo.Venturasetmessages: + msg135400
2011-05-06 22:58:35ezio.melottisetmessages: + msg135382
2011-05-06 22:57:14ezio.melottisetstatus: open -> closed

nosy: + ezio.melotti
messages: + msg135381

resolution: not a bug
stage: resolved
2011-05-06 22:53:04Rodrigo.Venturacreate