surprising interaction between function scope and class namespace
Stefan Behnel
stefan_ml at behnel.de
Mon Aug 15 05:50:58 EDT 2011
Stefan Behnel, 15.08.2011 11:33:
> 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.
... and an incorrect one, as it turns out. I think I misinterpreted the
results the wrong way around. Still:
> 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