global __dict__

Tim Peters at
Mon Dec 11 16:09:31 EST 2000

[posted & mailed]

[Carsten Geckeler]
> I was wondering if there is a __dict__ dictionary for the global
> namespace as for classes and modules.

Your terminology is a bit off:  you're *always* executing in a module in
Python.  "global namespace" has no other meaning than the namespace of the
module you're currently executing in.

> I was trying the following
> >>> var = 1
> >>> __dict__
> and expected that __dict__ would contain something like {..., 'var': 1},
> but there is no global __dict__.  Where can i find the global
> dictionary?

You need the module's __dict__.  In an interactive shell, you're running in
a module Python creates for you, named "__main__".  So:

>>> var = 1
>>> import __main__
>>> __main__.__dict__
{'__main__': <module '__main__' (built-in)>,
 '__doc__': None,
 'var': 1, # <------------------------------------- here's your vrbl "var"
 '__name__': '__main__',
 '__builtins__': <module '__builtin__' (built-in)>}

Somewhat easier is to use the globals() builtin function (which returns the
__dict__ for the module you're currently in):

>>> __main__.__dict__ is globals()

More information about the Python-list mailing list