bug in python's scope handling?
Steve Holden
sholden at holdenweb.com
Wed Jul 18 15:03:53 EDT 2001
----- Original Message -----
From: "Philipp Weinfurter" <philipprw at gmx.at>
Newsgroups: comp.lang.python
Sent: Wednesday, July 18, 2001 2:48 PM
Subject: Re: bug in python's scope handling?
> 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 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.
I know it's a little difficult to get your head around, but that's the
way it is! From section 4.1 of the 2.0 reference manual:
"""Whether a name is local or global in a code block is determined by
static inspection of the source text for the code block: in the absence
of global statements, a name that is bound anywhere in the code block is
local in the entire code block; all other names are considered global.
The global statement forces global interpretation of selected names
throughout the code block. The following constructs bind names: formal
parameters to functions, import statements, class and function
definitions (these bind the class or function name in the defining
block), and targets that are identifiers if occurring in an assignment,
for loop header, or in the second position of an except clause header.
Local names are searched only on the local namespace; global names are
searched only in the global and built-in namespace."""
regards
Steve
--
http://www.holdenweb.com/
More information about the Python-list
mailing list