[Python-Dev] LOAD_NAME & classes

Tim Peters tim.one@comcast.net
Mon, 22 Apr 2002 15:48:24 -0400


[Guido]
> ...
> Variable scope already violates the "only runtime" rule, and this has
> caused endless complaints and misunderstandings.

Any scope rules do:  you can't win here.  You can only choose which specific
rules cause endless complaints and misunderstandings.  Pure dynamic scoping
is the easiest for newcomers to understand, and it's a Bad Idea despite
that.

> Before nested scopes, I've toyed with the idea of making LOAD_FAST
> fall through (conceptually) to LOAD_GLOBAL when the local slot is NULL,
> just to shut up the complaints.  Then this example (whose failure
> always surprises newcomers)

It surprises some newcomers, plus Andrew Kuchling <wink>.

> would work:
>
>     x = 10
>     def f():
>         print x
>         x = 12
>     f()

But this still wouldn't:

    x = 10
    def f():
        print x

    def g():
        x = 12
        f()

    g()

You can't explain why that doesn't print 12 without insisting that different
textual regions have different scopes.  Newbie complaints and
misunderstandings follow.  Under an "only runtime" conception, the only
obvious behavior is that x is bound to 12 at the time f() is called, so of
course it should print 12.  It takes a certain sophistication to understand
that the name "x" means different things in different parts of the file.
Once that's understood, the behavior of your example is no longer a mystery;
but before it's understood, your example is only one of countless
confusions.  Indeed, the single most frequent newbie confusion I've heard
over the last year is variations on "OK, I did 'import math' like you said,
but 'sin(x)' *still* gives a NameError!".

> But now that we have nested scopes, I don't think this would be
> feasible -- the fallback would have to dynamically inspect all
> surrounding scopes.

As above, dynamic scoping is what newbies expect -- but it would be a great
disservice to give it to them.

pons-asinorum-ly y'rs  - tim