wasm-demo/demo/ermis-f/python_m/cur/0439

92 lines
2.9 KiB
Plaintext

From: tismer at appliedbiometrics.com (Christian Tismer)
Date: Sat, 10 Apr 1999 12:14:50 GMT
Subject: import from user input? What about 'from'?
References: <816010E2456BD111A48700805FBBE2EEA63EB9@ex-quebec-u1.baan.com>
<370E0F51.E1D33D6@appliedbiometrics.com> <370E4EFB.3D9355BF@vision.arc.nasa.gov>
Message-ID: <370F40BA.A1A28A1B@appliedbiometrics.com>
Content-Length: 2515
X-UID: 439
Chad Netzer wrote:
> 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)
Yes, this is ok with a single module and a single object in the
module. But for a full
from package.subpackage.module import object
you need to read the description of __import__ in section 2.3 of the
Python Library Reference and do a bit more.
Using the full __import__ syntax of
__import__ (name[, globals[, locals[, fromlist]]])
import package.subpackage.module
must be handled in a way that "package" goes into your module,
but "subpackage" gets imported into "package", and
"module" gets imported into "subpackage".
WHich means, our handle's name to be put into globals
is "package". On the other hand, for a
from package.subpackage.module import object
we need to work downhill from "package" to "module" and
pick the attribute "object", and we don't insert any
module into globals.
Example:
>>> target = "constants"
>>> modname = "win32com.client"
>>> fromlist = ["client"]
>>> glob = globals()
>>> loc=locals()
>>> glob[target] = getattr(__import__(modname, glob, loc, fromlist), target)
>>> constants
<win32com.client.Constants instance at 1608e50>
>>>
This the exact equivalent of
from win32com.client import constants
Please don't ask me why fromlist has to be a list, dunno.
But its non-emptiness makes __import__ return the last,
not the first element in pi.pa.po .
To get the full idea what happens, I'd further read the module
knee.py, which is a description what happens internally today.
Maybe someone can explain the details of fromlist to me :-)
ciao - chris
--
Christian Tismer :^) <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH : Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101 : *Starship* http://starship.python.net
10553 Berlin : PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint E182 71C7 1A9D 66E9 9D15 D3CC D4D7 93E2 1FAE F6DF
we're tired of banana software - shipped green, ripens at home