dynamic import
Duncan Booth
me at privacy.net
Fri Jul 23 08:21:35 EDT 2004
bry at itnisk.com wrote in
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"
>
> 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?
No. The import statement takes the name of a module, it doesn't take a
string. For example, instead of:
import sys
print sys.version
you are trying to do the equivalent of:
import "sys"
print "sys".version
You wouldn't expect the second line to work, so why should you expect the
first line to work? If it did work, how would you expect to refer to the
module it imported?
In this case your solution is to use the __import__ builtin. My example
becomes:
module = __import__("sys")
print module.version
More information about the Python-list
mailing list