bug in python's scope handling?

Philipp Weinfurter philipprw at gmx.at
Wed Jul 18 21:35:32 CEST 2001


On Wed, 18 Jul 2001 15:03:53 -0400, Steve Holden <sholden at holdenweb.com> wrote:
>> yes, this is what i thought. but is it correct?
>> i don't mean to be pedantic, but the rules are that if a variable
>> is not found in local scope, then the compiler looks up the global
>> scope and python doesn't follow this rule here.
>> it doesn't really hurt, since in 99% of all cases the programmer
>> probably _thinks_ he is referring to a local variable, but still...
> 
> The rules are correct, but you are making the mistake of assuming that
> Python determines the locality of local names by searching the
> namespace. This is where you are wrong. The compiler performs a static
> program analysis of each function, and if it sees assignments to a
> particular name (or indeed various other bindings, as described below)
> then it optimizes ALL references to that name to be local.

wait, do you mean that this is also true for assignments that occur
_after_ the statement in question?
let's try it out:
a = 1
def confuse_me():
    b = a + 1
    a = 0

confuse_me()
UnboundLocalError

aah.
now i see. i'm not sure that i like it, but i understand :)

thank you,
philipp



More information about the Python-list mailing list