[Python-Dev] __import__ problems

Mart Somermaa mrts at mrts.pri.ee
Thu Nov 27 23:39:14 CET 2008

Nick Coghlan wrote:
> i.e.
> "from foo.bar import baz" ---->
> <stack top> = __import__('foo.bar', globals(), locals(), ['baz'], -1)
> baz = <stack top>.baz
> When there are multiple names being imported or an 'as' clause is
> involved, I hope the reasons for doing it this way become more obvious:
> "from foo.bar import baz, bob" ---->
> <stack top> = __import__('foo.bar', globals(), locals(), ['baz', 'bob'], -1)
> baz = <stack top>.baz
> bob = <stack top>.bob
> "from foo.bar import baz as bob" ---->
> <stack top> = __import__('foo.bar', globals(), locals(), ['baz', 'bob'], -1)
> bob = <stack top>.baz

Thanks for clarifying this! I'd say the current wording of the docs is 
in that regard and your examples would be a nice addition to them.

> There's a perfectly correct approach documented as part of the
> __import__ docs that you referenced in your original email. If
> developers decide not to use that approach and use an undocumented hack
> instead, they have no right to complain when their code doesn't work
> properly.

There's a good reason for the hack -- the documented loop over components
+ getattr is both a bit ugly and inefficient (as is
fromlist=[modname.rsplit(".", 1)[-1]]). The variant proposed by Hrvoje 

 >>> __import__(modname)
 >>> mod = sys.modules[modname]

looks more appealing, but comes with the drawback that sys has to be 
imported for
that purpose only.

As none of the variants is really in the spirit of Python's zen and the 
use case
"given a string of dotted module names, import the tail module" is 
really common,
I'd still say we should go with the flow and provide people what they 
need explicitly
(i.e. something in the lines of  http://bugs.python.org/issue4438 ) -- 
and disable
the hack on the same occasion (by the way, is there a reason why both
__import__('foo', fromlist=['invalid']) and __import__('foo', 
fromlist=['']) don't raise
an error as of now?). This way the hacks will be eventually fixed in all 
those 2000
lines listed in Google Code.

Perhaps 3.1 and 2.7 would be an appropriate chance for that?

More information about the Python-Dev mailing list