Create object from variable indirect reference?
jhermann
Juergen.Hermann at 1und1.de
Tue Nov 17 04:26:00 EST 2009
On 10 Nov., 17:03, NickC <reply... at works.fine.invalid> wrote:
> Many thanks for the replies. getattr() works great:
You can get a little more versatile and even specify the location of
the name (i.e. the module / package name) without pre-importing it,
like this...
def importName(modulename, name=None):
""" Import identifier C{name} from module C{modulename}.
If name is omitted, modulename must contain the name after the
module path, delimited by a colon.
@param modulename: Fully qualified module name, e.g. C{x.y.z}.
@param name: Name to import from C{modulename}.
@return: Requested object.
@rtype: object
"""
if name is None:
modulename, name = modulename.split(':', 1)
module = __import__(modulename, globals(), {}, [name])
return getattr(module, name)
print importName("socket:gethostname")()
This is especially useful if you want to specify factory classes or
the like in a non-python config file. The syntax is the same as that
of setuptools entry points.
More information about the Python-list
mailing list