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


Groups > comp.lang.python > #11448

surprising interaction between function scope and class namespace

From Stefan Behnel <stefan_ml@behnel.de>
Subject surprising interaction between function scope and class namespace
Date 2011-08-15 11:33 +0200
Newsgroups comp.lang.python
Message-ID <mailman.5.1313400826.27778.python-list@python.org> (permalink)

Show all headers | View raw


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

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


Thread

surprising interaction between function scope and class namespace Stefan Behnel <stefan_ml@behnel.de> - 2011-08-15 11:33 +0200
  Re: surprising interaction between function scope and class namespace Duncan Booth <duncan.booth@invalid.invalid> - 2011-08-15 10:18 +0000
  Re: surprising interaction between function scope and class namespace Peter Otten <__peter__@web.de> - 2011-08-15 12:42 +0200
    Re: surprising interaction between function scope and class namespace Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-08-16 13:08 +1200

csiph-web