Quirk difference between classes and functions

Chris Angelico rosuav at gmail.com
Tue Feb 26 20:24:46 EST 2019


On Wed, Feb 27, 2019 at 12:21 PM <jfong at ms4.hinet.net> wrote:
>
> Gregory Ewing at 2019/2/27 AM 5:26:49 wrote:
> > Thomas Jollans wrote:
> > > I imagine there's a justification for the difference in behaviour to do
> > > with the fact that the body of a class is only ever executed once, while
> > > the body of a function is executed multiple times.
> >
> > I suspect there isn't any deep reason for it, rather it's just
> > something that fell out of the implementation, in particular
> > the decision to optimise local variable access in functions
> > but not other scopes.
> >
> > When compiling a function, the compiler needs to know which
> > variables are local so that it can allocate slots for them in
> > the stack frame. But when executing a class body, the locals
> > are kept in a dict and are looked up dynamically.
>
> If the compiler can do any decision on the variable's name, when it goes to line of print, how it handle it?
>
> x = 0
> def f():
>     print(x)
>
> def g():
>     print(x)
>     x = 1
>     print(y)
>

Not sure what you mean by "decision", but the definition is that since
x is assigned to in g(), it is local to g(). It's not local to f(), so
the global is visible.

(Incidentally, "print" is handled exactly the same way. Since neither
function assigns to print, it's not local, so the built-in is found.)

ChrisA



More information about the Python-list mailing list