From: chad at vision.arc.nasa.gov (Chad Netzer)
Date: Fri, 09 Apr 1999 12:03:23 -0700
Subject: import from user input?  What about 'from'?
References: <816010E2456BD111A48700805FBBE2EEA63EB9@ex-quebec-u1.baan.com> <370E0F51.E1D33D6@appliedbiometrics.com>
Message-ID: <370E4EFB.3D9355BF@vision.arc.nasa.gov>
Content-Length: 1091
X-UID: 1483                                                  

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






