surprising interaction between function scope and class namespace

Duncan Booth duncan.booth at invalid.invalid
Mon Aug 15 06:18:03 EDT 2011

Stefan Behnel <stefan_ml at> 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 

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 
should say something about this but it doesn't. 

Duncan Booth

More information about the Python-list mailing list