surprising interaction between function scope and class namespace

Gregory Ewing greg.ewing at
Tue Aug 16 03:08:36 CEST 2011

Peter Otten wrote:

> LOAD_NAME is pretty dumb, it looks into the local namespace and if that 
> lookup fails falls back to the global namespace. Someone probably thought "I 
> can do better", and reused the static name lookup for nested functions for 
> names that occur only on the right-hand side of assignments in a class.

I doubt that it was a conscious decision -- it just falls
out of the way the compiler looks up names in its symbol
table. In case 1, the compiler finds the name 'a' in
the function's local namespace and generates a LOAD_FAST
opcode, because that's what it does for all function-local
names. In case 2, it finds it in the local namespace of
the class and generates LOAD_NAME, because that's what
it does for all class-local names.

The weirdness arises because classes make use of vestiges
of the old two-namespace system, which bypasses lexical
scoping at run time.


More information about the Python-list mailing list