__import__ confusion

Steven Taschuk staschuk at telusplanet.net
Tue Feb 25 06:42:29 CET 2003

Quoth Leazen:
> 	I'm having some trouble understanding how __import__ works.
> 	From the docs I read that "from spam.ham import eggs" results in
> "__import__('spam.ham', globals(), locals(), ['eggs'])" rendering the
> later function call 'eggs', what ever that is, but I actually get 'ham'!

I've just read the blurb on __import__ in section 2.1 of the
Library Reference, and I don't see anything to indicate that it
returns the things named in the last argument.  On the contrary:

    When the name variable is of the form package.module, normally,
    the top-level package (the name up till the first dot) is
    returned, not the module named by name. However, when a non-empty
    fromlist argument is given, the module named by name is returned.

The last sentence indicates that __import__('spam.ham', globals(),
locals(), ['eggs']) will return the module named spam.ham, as you
have found.

> [...] So I wonder what the last argument is for since it seams rather
> useless. [...]

Some implementations of __import__ might find it useful -- it
might be possible in some circumstances to optimize the import if
you know precisely which components are needed.

Steven Taschuk                               staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
                            -- Tony Dylan Davis (CKUA)

More information about the Python-list mailing list