[Python-Dev] LOAD_NAME & classes
Tue, 23 Apr 2002 11:30:59 -0400
> > [Guido van Rossum]
> > > We need more than a single example to decide which rules bites worse
> > > for large programs. Deep nesting is not common; long functions are.
> > > And there the common annoyance is that a change in line 150 can break
> > > the code in line 2 of the function.
> > I'm not exactly sure what you mean by this. Can you share an
> > example? (Not necessarily 150+ lines long, of course.) Thanks.
> It's a classic. Before we had UnboundLocalError (i.e. in 1.5.2 and
> before) this was a common problem on c.l.py:
> x = "a global"
> def f():
> print x # user thinks this should print the global
> # 2000 lines of unrelated code
> for x in "some sequence": # doesn't realize this overrides x
> Calling f() would raise NameError: x, which caused lots of confusion.
> We added UnboundLocalError th make it clearer what's going on (so at
> least the experienced c.l.py users would know right away where the
> problem was :-), but still requires you to know about something
> obscure that's going on at compile time (the compiler scanning your
> entire function for variable definitions).
So, the problem is the implicit local declaration that assumed when the
compiler detects a binding lower down the function's code than the first
reference to it, coupled with their function-wide scope. It is compounded by
the fact that although the analysis is performed at compile time the error
is only reported at run time.
Might it make more sense to issue a warning at compile time to the effect
that a variable is being used before it's assigned? How completely are
(re)bindings detected by the static analysis? Can you necessarily guarantee
that a LOAD_FAST is always looking at a local name? [You'll understand I'm
not familiar with the details of code generation].
Seems to me the real problem here is explaining (by the interpreter's
behavior, rather than in the documentation ;-) the scope of locals and how a
name is determined to be local. It might help beginners if there was some
really easy way to get a fuller explanation of an error message. Not sure
how best that could be retrofitted, but it's better than code breakage.
Unfortunately the scoping rules are now "in the wild", so it's not possible
to change things too radically without mucho pain for those who have already
relied on them.
Python Web Programming: