This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mrts
Recipients mrts
Date 2008-11-26.11:58:30
SpamBayes Score 5.3545834e-10
Marked as misclassified No
Message-id <1227700719.4.0.771610572152.issue4438@psf.upfronthosting.co.za>
In-reply-to
Content
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'>
History
Date User Action Args
2008-11-26 11:58:39mrtssetrecipients: + mrts
2008-11-26 11:58:39mrtssetmessageid: <1227700719.4.0.771610572152.issue4438@psf.upfronthosting.co.za>
2008-11-26 11:58:37mrtslinkissue4438 messages
2008-11-26 11:58:35mrtscreate