bug in python's scope handling?

Bjorn Pettersen BPettersen at NAREX.com
Wed Jul 18 15:10:59 EDT 2001


> From: Philipp Weinfurter [mailto:philipprw at gmx.at]
> 
> On Wed, 18 Jul 2001 14:20:49 -0400, Steve Holden 
> <sholden at holdenweb.com> wrote:
> > When your Python is compiled into bytecode, the assignment 
> to a is detected
> > during compilation of your function func2(). The name a is 
> therefore assumed
> > to refer to a local variable, hence the ruin-time exception 
> you observe.
> 
> 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 a little more complicated:

 1. if a variable is assigned to anywhere in a function,
    then all mentions of the variable in the current function
    are references to this local.
 2. during lookup, if a name can't be found in the local scope, 
    the global scope will be used.

therefore it's allready decided before the lookup phase whether the
variable is a local or a global. Is it correct? Well, it removes a
number of possible errors, so yes. <wink>

-- bjorn




More information about the Python-list mailing list