Message76460
The need to dynamically import module foo given a module name string
'bar.baz.foo' is quite common.
Quite often, the hack described in http://bugs.python.org/issue2090 is
used (see e.g. the Google code results linked from the issue).
Quoting Brett Cannon from the issue:
"I plan to add a much simpler API to the imp module for people to use
directly so that these abuses don't continue."
Although there are reasonable workarounds, let the current ticket be a
remainder for Brett that his plan is indeed needed.
Perhaps the easiest thing to do would be to add yet another argument,
e.g. 'toplevel', to __import__, such that:
>>> __import__('imprt.foo.foo') # toplevel=True by default
<module 'imprt' from 'imprt/__init__.pyc'>
>>> __import__('imprt.foo.foo', toplevel=False)
<module 'imprt.foo.foo' from 'imprt/foo/foo.pyc'>
The latter can currently be achieved by
>>> __import__('imprt.foo.foo', {}, {}, ['foo'])
<module 'imprt.foo.foo' from 'imprt/foo/foo.pyc'>
which is cumbersome if the module name is given in a string, resulting
in unnecessarily complex code:
modname = "imprt.foo.foo"
>>> __import__(modname, {}, {}, [modname.rsplit(".", 1)[-1]])
<module 'imprt.foo.foo' from 'imprt/foo/foo.pyc'> |
|
Date |
User |
Action |
Args |
2008-11-26 11:58:39 | mrts | set | recipients:
+ mrts |
2008-11-26 11:58:39 | mrts | set | messageid: <1227700719.4.0.771610572152.issue4438@psf.upfronthosting.co.za> |
2008-11-26 11:58:37 | mrts | link | issue4438 messages |
2008-11-26 11:58:35 | mrts | create | |
|