[Tutor] x is a global variable
davea at ieee.org
Tue Dec 1 02:04:10 CET 2009
> Hello Eike!
> Eike Welk <eike.welk at gmx.net> dixit:
> Well, this is certainly not specific to closures.
> i = 0
> def f():
> i = i+1
> print i
> ==> UnboundLocalError
> Imo, in this case, "i = i+1" is a kind of "paradoxal injonction" (lol! not sure of the exact idiom in english). You tell python both to create a local i (thus ignore any other scope to lookup for variables called 'i') and to use global i to define the local one.
> If I were the victim of such a "paradoxal injonction" I would reply with a naughty word!
I believe the easiest model to understand the behavior is:
The compiler scans the entire function to find which variables are
assigned (via =, as, or other syntax) anywhere in the function. Then
for those variables, all references are done without any dictionary
accesses. Thus an assignment anywhere (not just on the same line) cause
all references to be to the (unbound) local.
More information about the Tutor