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
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.
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