[Python-Dev] LOAD_NAME & classes

Patrick K. O'Brien pobrien@orbtech.com
Tue, 23 Apr 2002 10:22:28 -0500


[Guido van Rossum]
> > > 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
>             do_something_with(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).

Okay. I think I'm following you, but I want to be certain about the
statement that "a change in line 150 can break the code in line 2 of the
function." Using your example, the function f() works, but only because of a
"fortunate" side effect of sorts. So if the code was later changed to "for y
in ..." then f() no longer works. But the example is fundamentally flawed to
begin with. Proper code shouldn't have to worry that "a change in line 150
can break the code in line 2 of the function." Right? Or am I still missing
something?

I've never felt that I needed to know about something obscure going on at
compile time in order to write decent Python code. Maybe I'm just being
paranoid, but this whole discussion just struck me as odd because I can't
recall ever having any problem like this. For the most part Python does
exactly what I think it should do. And when it doesn't, I'm usually wrong.

---
Patrick K. O'Brien
Orbtech