dynamic import

Peter Otten __peter__ at web.de
Fri Jul 23 08:22:26 EDT 2004


bry at itnisk.com wrote:

> I'm trying to do a dynamic import of a file that has no problems with it,
> that is to say I can import it normally, my sys.path is set to the right
> folder etc. but my dynamic import code is not working, this is the problem
> code:
> 
> try:
>     import f[0]
> except:
>     print "not importable"
>   
> f[0] returns the name of the file I'm importing, so I suppose this is a
> typing problem, should I change f[0] to be some other type?
> 
> I've also tried
> t = "import " + f[0]
>     try:
>         eval(t)
>     except:
> print "not importable"
>         
> but I always get "not importable"

Let's see.

>>> import f[0]
  File "<stdin>", line 1
    import f[0]
            ^
SyntaxError: invalid syntax

So python won't accept the [0] stuff here.

>>> f = "os"
>>> import f
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: No module named f

So python doesnt try to resolve f as a variable name but rather as a
literal.

>>> eval("import os")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1
    import os
         ^
SyntaxError: invalid syntax
>>> exec "import os"

So the eval() function chokes if you feed it an import statement (actually
any statement).

Quoted from http://docs.python.org/lib/built-in-funcs.html#l2h-23 

"""Hints: dynamic execution of statements is supported by the exec
statement."""

Putting it together:

>>>>> f = ["os"]
>>> exec "import " + f[0]
>>> os
<module 'os' from '/usr/local/lib/python2.3/os.pyc'>

Heureka :-)

Now, did you see how useful Python's tracebacks are and how much information
you lose by a bare try ... except?

try:
   ...
except ImportError:
   ...

would have been fine, by the way.

Peter




More information about the Python-list mailing list