Message110234
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__ |
|
Date |
User |
Action |
Args |
2010-07-13 21:49:29 | belopolsky | set | recipients:
+ belopolsky, brett.cannon |
2010-07-13 21:49:29 | belopolsky | set | messageid: <1279057769.02.0.398615806235.issue9254@psf.upfronthosting.co.za> |
2010-07-13 21:49:27 | belopolsky | link | issue9254 messages |
2010-07-13 21:49:27 | belopolsky | create | |
|