[New-bugs-announce] [issue4438] Add an easy way to __import___ submodules

Mart Sõmermaa report at bugs.python.org
Wed Nov 26 12:58:39 CET 2008


New submission from Mart Sõmermaa <mrts at mrts.pri.ee>:

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'>

----------
components: Interpreter Core, Library (Lib)
messages: 76460
nosy: mrts
severity: normal
status: open
title: Add an easy way to __import___ submodules
type: feature request
versions: Python 2.7, Python 3.1

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue4438>
_______________________________________


More information about the New-bugs-announce mailing list