Can import a user-specified module?
Peter Hansen
peter at engcorp.com
Tue Aug 13 22:24:06 EDT 2002
Erik Max Francis wrote:
>
> Sung Kim wrote:
>
> > In Python, is something like the following pseudo-code possible? Thank
> > you!
> >
> > moduleName = GetNameFromUser ()
> >
> > import moduleName
> >
> > if moduleName.SomeFunction exists
> > x = moduleName.SomeFunction ()
>
> Try the __import__ function:
>
> __import__(moduleName)
> if moduleName.__dict__.has_key(functionName):
> moduleName[functionName]()
Buglet? I think moduleName is still a string in the above if statement,
and you can't use the dictionary lookup in the function call line
on either the string or a real module.
This might be better:
mymod = __import__(moduleName)
if hasattr(mymod, functionName):
getattr(mymod, functionName)()
Note that there is no guarantee in these snippets that
functionName really refers to a _callable_ item unless
you use callable() in a test as well.
-Peter
More information about the Python-list
mailing list