Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #11449

Re: surprising interaction between function scope and class namespace

From Stefan Behnel <stefan_ml@behnel.de>
Subject Re: surprising interaction between function scope and class namespace
Date 2011-08-15 11:50 +0200
References <j2ap58$pn0$1@dough.gmane.org>
Newsgroups comp.lang.python
Message-ID <mailman.6.1313401876.27778.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: surprising interaction between function scope and class namespace Stefan Behnel <stefan_ml@behnel.de> - 2011-08-15 11:50 +0200

csiph-web