surprising interaction between function scope and class namespace

Stefan Behnel stefan_ml at behnel.de
Mon Aug 15 11:33:28 CEST 2011


Hi,

I just stumbled over this:

   >>> A = 1
   >>> def foo(x):
   ...     A = x
   ...     class X:
   ...         a = A
   ...     return X
   ...
   >>> foo(2).a
   2
   >>> def foo(x):
   ...     A = x
   ...     class X:
   ...         A = A
   ...     return X
   ...
   >>> foo(2).A
   1

Works that way in Py2.7 and Py3.3.

I couldn't find any documentation on this, but my *guess* about the 
reasoning is that the second case contains an assignment to A inside of the 
class namespace, and assignments make a variable local to a scope, in this 
case, the function scope. Therefore, the A on the rhs is looked up in that 
scope as well. However, this is just a totally hand waving guess.

Does anyone have a better explanation or know of a place where this 
specific behaviour is documented?

Stefan




More information about the Python-list mailing list