[Python-Dev] LOAD_NAME & classes

Guido van Rossum guido@python.org
Tue, 23 Apr 2002 11:33:38 -0400

> 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.

Why is the fact that this works:

    x = 12
    def f():
        print x

a "fortunate" side effect?  That's how the language works!

> 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 think you've got it backwards.  My complaint is that if f() above
eventually grew 150 lines of unrelated code ending with an unrelated
assignment to a local variable x, the breakage would show up at an
unexpected point.  Except for this one, it's hard to make a change at
the *tail* of a function that breaks something at the beginning!

> 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.

This particular form of breakage was a common error reported on c.l.py
and to help at python.org until we added UnboundLocalError to make the
diagnostic cleaner.  Maybe that's all that's needed; getting a
NameError when you see this:

    x = 12
    def f():
        print x    # <--- NameError raised here!
        ...150 line of code you didn't think could cause the problem...

was very disturbing, causing people to look for places where x was
deleted from the global namespace later in the program.

--Guido van Rossum (home page: http://www.python.org/~guido/)