[New-bugs-announce] [issue9254] __import__ docstring should recommend importlib.import_module()

Alexander Belopolsky report at bugs.python.org
Tue Jul 13 23:49:29 CEST 2010

New submission from Alexander Belopolsky <belopolsky at users.sourceforge.net>:

On Tue, Jul 13, 2010 at 4:52 PM, Brett Cannon wrote [1]:
> I say this every time I give an import talk and it has been brought up here
> before but obviously not everyone catches it (which is understandable as I
> think when it came up on python-dev it was at the tail end of a discussion),
> so I am just going to repeat myself:
>   Do not put junk in fromlist if you call __import__ directly! Use
> importlib.import_module! Or if you have a *really* good reason to not use
> it, then use ``__import__(name); module = sys.modules[name]``.

I think one of the reasons the message does not sink in (at least this is the reason in my case) is that a user who discovers that __import__('foo.bar') returns foo instead of bar, looks up help(__import__) to find that

When importing a module from a package, note that __import__('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty.

Passing fromlist=["dummy"] seems like a natural solution after reading this.

The ReST documentation [2] is slightly better as it contain a recommendation that says: "If you simply want to import a module (potentially within a package) by name, you can call __import__() and then look it up in sys.modules." However this still fails to mention the (better IMO) alternative of using importlib.import_module().

I believe the __import__ docstring should start with a recommendation not to use it directly and use importlib.import_module() instead, while the ReST documentation should grow a warning not to use dummy fromlist and the recommendation to use __import__() followed by sys.modules lookup should be changed to a recommendation to use mportlib.import_module().

[1] "Peculiar import code in pickle.py" <http://mail.python.org/pipermail/python-dev/2010-July/101906.html>.
[2] http://docs.python.org/dev/library/functions.html?#__import__

messages: 110234
nosy: belopolsky, brett.cannon
priority: normal
severity: normal
status: open
title: __import__ docstring should recommend importlib.import_module()

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list