import from user input? What about 'from'?

Chad Netzer chad at vision.arc.nasa.gov
Fri Apr 9 15:03:23 EDT 1999


Gaetan Corneau wrote:


> I want to import modules at runtime, and get the module name from the user.
> Is that possible? How?
>
>
Christian Tismer wrote:

> Instead, one should cut off the first name before the first dot
> and put that into globals().
>
> import string
> globals()[string.split(modname, ".")[0]] = __import__(modname)
>
> seems to do it better.

Hmm, what if I want to do something like:

exec 'from ' + module_name + ' import ' + class_name

Can I use the __import__call, and then just save the specific module name in globals()?
ie. (minus exception checking):

    globals()[class_name] = getattr(__import__(module_name), class_name)

Hell, I can just try it...

% python
Python 1.5.2b2 (#2, Apr  2 1999, 17:30:13) [C] on irix6
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> globals()['strip'] = getattr(__import__('string'), 'strip')
>>> globals()
{'strip': <built-in function strip>, '__doc__': None, '__name__': '__main__', '__builtins__': <module '__builtin__'
(built-in)>}


Looks ok to me... Neat!.

Chad Netzer
chad at vision.arc.nasa.gov






More information about the Python-list mailing list