vars() and dir()

Peter Hansen peter at engcorp.com
Thu Aug 26 08:54:13 EDT 2004


Claire wrote:

> i use vars() or dir() to get variables. I use them in a def block, so
> i get variables of that block. How can i get variables from the
> namespace __main__ ?

vars(__main__) or dir(__main__) works if you import __main__ first.

> I use python in interactive mode and want to have a function to get a
> dictionnary for python types (int, ...) and another for my types (my
> classes). this function will be in my pythonstartup file.
> 
> If i use python in interactive mode, is there a main module defined ?

Yes, but you always have to import stuff before you can use it.  Do
import __main__ and it gives you an alias for the current namespace,
but the result is the same as using plain vars() or dir() there.

> i don't know how to use namespace __main__ to get information on this
> "global namespace" like i can do with math or another module

No difference, just import first.

If this doesn't help, please try explaining further what you are
trying to accomplish.  I don't think it's entirely clear from what you
have said above.

-Peter



More information about the Python-list mailing list