[Python-Dev] LOAD_NAME & classes

Guido van Rossum guido@python.org
Mon, 22 Apr 2002 14:39:12 -0400

> >>>>> "GvR" == Guido van Rossum <guido@python.org> writes:
> > def f(x):
> >     class Foo:
> >         x = x
> > 
> > and 
> > 
> > x = 1
> > class Foo:
> >     x = x
>   GvR> I just tried this in 2.1 (without nested scopes enabled) and
>   GvR> there the first example fails too.
> I think you misunderstood my original explanation.  With the current
> implementations, the first example fails and the second example
> works.  I think the bug is that the second example works.

But it has always worked, and I definitely don't want to break this

I don't understand why you want to break it?  That would definitely
break working code!

>   GvR> While it's slightly confusing, it's consistent with the rule
>   GvR> that class bodies don't play the nested scopes game, and I
>   GvR> think it shouldn't be fixed.  Otherwise you'd have the
>   GvR> confusing issue that a function inside a class can't see the
>   GvR> class scope, but a class inside a function can see the function
>   GvR> scope.  Better if neither can see the other.
> None of the documentation suggests that class and functions don't see
> each other.  Rather, it says the free variables are resolved in the
> nearest enclosing function scope.

Oops, I misremembered how this works.

> The current implementation supports resolution of free variables in
> class scope, e.g.
> def f(x):
>     class Foo:
>         print x
> >>> f(3)
> 3
> I think the problem is with x = x, which ought to be an error if x is
> a local and x is unbound.  The code will succeed, nested or otherwise,
> if x happens to be a module global.  The confusion is that the code
> will not succeed if x is defined in an enclosing, non-top-level
> scope.

Nested scopes in Python will never be completely intuitive, because
they break the illusion that "there's only runtime" (as Samuele
summarized it a while ago).

That said, I can't decide whether it's better to make the first
example work, or reject the bug report.  I'm tempted to say "the ice
is thin here, don't play with fire" or something cryptic like that,
and leave it.

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