Quirk difference between classes and functions
greg.ewing at canterbury.ac.nz
Tue Feb 26 16:26:35 EST 2019
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.
The compiler *could* be made to treat class bodies the same
way as functions in this regard, but it would be extra work
for little or no benefit. Most code in class bodies just
defines new names without referring to anything else in the
More information about the Python-list