Namespaces in functions vs classes

Ethan Furman ethan at
Tue Apr 19 12:31:39 EDT 2011

Gerald Britton wrote:
> I now understand the Python does
> not consider a class definition as a separate namespace as it does for
> function definitions.  That is a helpful understanding.

That is not correct.  Classes are separate namespaces -- they just 
aren't automatically searched.  The only namespaces that are 
automatically searched are local, non-local, global, and built-in.

Similarly, if you have a dictionary of values

--> d = {'eggs':'green', 'method':'train'}

then 'd' is a namespace, but if you're function/method/whatever just tries:

--> if method == 'boat':
-->     blah()

then you'll get a NameError because the 'd' namespace will not be 
automatically searched.  You would have to do:

--> if d['method'] == 'boat':
-->     blah()

to find the variable in that namespace.

Hope this helps.


More information about the Python-list mailing list