__import__ .vs. sys.modules

holger krekel pyth at devel.trillke.net
Fri May 31 12:35:29 EDT 2002


Fran?ois Pinard wrote:
> Hello, people.
> 
> Yesterday, someone suggested on this list that:
> 
>         module = sys.modules[__name__]
> 
> should best be written:
> 
>         module = __import__(__name__)

Yesterday i was thinking that '__name__' refers
to the usual preset __name__ from python inside
a module. And this should not have a dot if i am not
mistaken.

For example the 'os.path' module is explicitely bound
by the os-module with 'sys.modules['os.path']=...' 
(just have a look in the source).

> This looked nice to me, at first.  However, if `__name__' contains dots,
> only the first of the above writing works.  The second could be made to
> work by splitting `__name__' at periods and doing more stunts after that,
> but then, it becomes heavier and does not seem worth all the trouble.

So yes, if you have some variable containing any 
(possibly dotted) module name than 

    module = sys.modules[somestring] 

is the general approach. Note that using this approach 
the module must be already loaded. 

__import__ can handle the case with dotted modulenames as well
(lookup the docs for this extended usage) but it would automatically
try to load the modules.

regards,

    holger





More information about the Python-list mailing list