dynamic import

John Roth newsgroups at jhrothjr.com
Fri Jul 23 08:44:33 EDT 2004


<bry at itnisk.com> wrote in message
news:mailman.750.1090583812.5135.python-list at python.org...
> Hi,
> 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"

the import statement unfortunately doesn't take a string at
run time. As Duncan says, you need to use the
__import__() builtin. Read up on it in the library
reference (it's the very first entry in the builtins section,)
because there are some considerations in using it that
aren't exactly obvious on first glance.

The other alternative is something like:

exec "import " + f[0]

This will work as well, and it might be a bit clearer, depending
on what you're trying to do.

John Roth





More information about the Python-list mailing list