Accessing global namespace

Peter Hansen peter at engcorp.com
Mon Oct 6 12:30:39 EDT 2003


Tonguç Yumruk wrote:
> 
> I'm trying to build a completely plug-in based system. One of my
> problems is importing a package dynamically. I'm trying to emulate the
> import command. The __import__() function or imp module doesn't help me
> much because they only return the module. I want to register the module
> with it's name in the current namespace. I can do it by:
> 
>         globals()[module_name] = __import__(module_name)
> 
> But I don't think it's a good thing to access the global namespace
> directly. 

There's nothing wrong with "accessing the global namespace directly"
like that.  In fact, that's pretty much the only way (though it's not
in itself sufficient) to emulate the "import" statement when you want
a dynamic import.

In general, you need to (a) import with __imoprt__, (b) insert name
into sys.modules dictionary, and (c) insert name into globals().  What
you are doing above is the proper way to do that, IMHO.

-Peter




More information about the Python-list mailing list