unable to read the __main__ namespace
Peter Otten
__peter__ at web.de
Sun Dec 13 06:34:11 EST 2009
vsoler wrote:
> I'm learning Python, and I am very fond of it.
>
> Using Python 2.6
>
> I am able to list all the names in a class namespace:
>
> class abc: pass
> abc.a1=7
> abc.a2='Text'
>
> print abc.__dict__.keys()
>
> a) However, I do not know how to read the __main__ namespace
>
> print __main__.__dict__.keys() # Just does not work
It should work. Did you forget to
import __main__
before trying?
> b) How do i read an imported module namespace?
>
> c) How could I possibly list the names and contents of the namespace
> of my python session?
The answer to all your questions is dir() for names and vars() for the
complete namespace dictionary:
>>> x = 42
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'x']
>>> import os
>>> dir(os)[:5]
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST']
>>> vars()
{'__builtins__': <module '__builtin__' (built-in)>, '__package__': None,
'x': 42, '__name__': '__main__', 'os': <module 'os' from
'/usr/lib/python2.6/os.pyc'>, '__doc__': None}
Peter
More information about the Python-list
mailing list