function to do dynamic import?

Steve Holden steve at holdenweb.com
Tue Sep 11 08:24:39 EDT 2007


bambam wrote:
> import works in the main section of the module, but does
> not work as I hoped when run inside a function.
> 
> That is, the modules import correctly, but are not visible to
> the enclosing (global) scope.
> 
> Questions:
> (1) Where can I read an explanation of this?
> (2) Is there a work around?
> 
> BTW, sys.modules("filename") shows that the module is
> loaded, I just don't know how to use it when loaded that
> way.  Also, if I import again at the global scope, the module
> name becomes available.
> 
There's not much wrong with doing this, since it gives you the best of 
both worlds. But you mean sys.modules["filename"], don't you?

>>>> def gim():
> ... exec "import gamel"
> ...
>>>> gim()
>>>> sys.modules["gamel"]
> <module 'gamel' from 'c:\gamel.pyc'>
>>>> gamel
> NameError: name 'gamel' is not defined
>>>> exec "import gamel"
>>>> gamel
> <module 'gamel' from 'c:\gamel.pyc'> 
> 
> 
Whoa there! There's a lot of difference between "importing a module 
inside a function" and "executing an import statement inside a function".

If you want to do dynamic imports then the __import__ function is what 
you need. Trying to use exec like that is a bad idea unless you clearly 
understand the relationship between the different namespaces involved. 
In fact, trying to use exec at all is a bad idea until you understand 
Python better, and even then it's not often a terrific idea.

Think of exec more as a hack of last resort than the first tool to reach 
for to solve a problem.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list