[Tutor] namespaces and the __dict__ function?

Kent Johnson kent37 at tds.net
Fri Jan 25 20:15:22 CET 2008

John Gunderman wrote:
> I am new to python and have found both the concept of namespaces and the 
> __dict__ function to be rather confusing, and I cant find any good 
> explanations on the web. Could any of you give me a good explanation of 
> these? And for __dict__, is is the same thing as __str__ except in 
> string form, or does it store all current objects of that class in a 
> __dict__?

First, __dict__ is an attribute of an object whose value is a dict, not 
a function.

A namespace is a place where names can be defined. The official tutorial 
A namespace is a mapping from names to objects. Most namespaces are 
currently implemented as Python dictionaries... Examples of namespaces 
are: the set of built-in names (functions such as abs(), and built-in 
exception names); the global names in a module; and the local names in a 
function invocation. In a sense the set of attributes of an object also 
form a namespace.


Another way to think of it is, a namespace is a place where names are 
looked up. When you use a bare name (not an attribute), it is looked up 
in the local namespace, then the global namespace, then the built-in 
namespace. For example:

y = 2	# Defines y in the global (module) namespace

def f():
   x = 1 # Defines x in the local (function) namespace

   # This looks up x, finds it in the local namespace
   # looks up abs, finds it in the built-in namespace
   print abs(x)

   # This looks up y, finds it in the global namespace
   print y

Note that none of the above namespaces have a related __dict__ 
attribute, the namespace mappings are not stored that way.

Objects also define a sort of namespace, where attributes are defined 
and looked up. The dict containing the namespace of an object is itself 
stored as an attribute of the object, called __dict__. So __dict__ is an 
implementation detail of the way object attributes are stored.

As a beginner, it is important to understand the way bare names are 
looked up (local, global, built-in namespace) and a bit about the way 
attributes work. You don't have to be concerned with the implementation 
details such as __dict__.

(For completeness, I will say that the full attribute lookup model is 
much more complicated than I have indicated above. I have simplified to 
focus on __dict__.)


More information about the Tutor mailing list