dynamic import

Nick Smallbone nick at nick8325.freeserve.co.uk
Fri Jul 23 14:03:45 CEST 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,
> is to say I can import it normally, my sys.path is set to the right folder
> 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
> 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"

That's because eval evaluates an expression and returns the result. To
execute a statement you need to use exec(t) instead.


More information about the Python-list mailing list