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


Groups > comp.lang.python > #11451

Re: surprising interaction between function scope and class namespace

From Duncan Booth <duncan.booth@invalid.invalid>
Newsgroups comp.lang.python
Subject Re: surprising interaction between function scope and class namespace
Date 2011-08-15 10:18 +0000
Message-ID <Xns9F4271CDF768duncanbooth@127.0.0.1> (permalink)
References <mailman.5.1313400826.27778.python-list@python.org>

Show all headers | View raw


Stefan Behnel <stefan_ml@behnel.de> wrote:

> 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?
> 

If it was a function rather than a class then in the first case you look up 
the non-local variable as expected and in the second case you get an 
UnboundLocalError.

The only difference with the class definition is that instead of 
UnboundLocalError the lookup falls back to the global scope.

This happens because class definitions use LOAD_NAME/STORE_NAME instead of 
LOAD_FAST/STORE_FAST and LOAD_NAME looks first in local scope and then in 
global. I suspect that 
http://docs.python.org/reference/executionmodel.html#naming-and-binding 
should say something about this but it doesn't. 

-- 
Duncan Booth http://kupuguy.blogspot.com

Back to comp.lang.python | Previous | NextPrevious in thread | Next 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