How do i cast a string to be used as a module?

Hung Jung Lu hungjunglu at yahoo.com
Fri Mar 26 03:29:14 EST 2004


"sean" <sean_berry at cox.net> wrote in message news:<9kM8c.46388$Bg.39277 at fed1read03>...
> 
> But, what if I want to call a function from within this
> module that takes as an argument the name of a module.
> 
> For example if I was making a module like the following
> 
> import inspect
> 
> def functionname( modname ):
>     exec("import "+modname)
>     s = inspect.getsource( modname )
>     return s

Use s = inspect.getsource(sys.modules[modname]), of course, import sys
first.

Another thing that people often ask is how to access module level
variables by name string. The device there is the globals()
dictionary. So, remember that there are a few interesting namespace
dictionaries that come in handy:

(a) __builtin__ (it's a module, but you can access its namespace via
__builtin__.__dict__)
(b) globals() and locals()
(c) sys.modules
(d) os.environ
etc.

One has to be careful with the locals() dictionary (use it only as
read-only.)

regards,

Hung Jung



More information about the Python-list mailing list