[Import-SIG] Dabeaz's weird import discovery

Guido van Rossum guido at python.org
Wed Apr 22 19:37:11 CEST 2015

On Wed, Apr 22, 2015 at 10:33 AM, Eric Snow <ericsnowcurrently at gmail.com>

> On Wed, Apr 22, 2015 at 11:15 AM, Guido van Rossum <guido at python.org>
> wrote:
> > It's definitely intentional, and it's fundamental to the package import
> > design. We've had many implementations of package import (remember
> "ni.py"?
> > last seen as "knee.py") and it was always there, because this is done as
> > part of *submodule loading*. For better or for worse (and because I
> didn't
> > know Java at the time :-) Python declares that if you write `import
> foo.bar`
> > then later in your code you can use `foo.bar` to reference to the bar
> > submodule of package foo. And the way this is done is to make each
> submodule
> > an attribute of its parent package. This is done when the submodule is
> first
> > loaded, and because of the strict separation between loading and
> importing,
> > it is done no matter what form of import was used to load bar.
> Exactly.  "import spam.eggs; spam.eggs" looks up "spam" and then its
> "eggs" attribute, so "eggs" has to be bound during the import.
> The surprising part is that it also happens for explicit relative
> imports.  I'm guessing that part was unintentional and simply not
> noticed when PEP 328 was implemented.

No, that must also have been intentional, because even when you use
relative import, the module you imported knows its full name, and that full
name is used as its key in sys.modules. If someone else uses absolute
import for the same module they should still get the same module object.

> > I guess another thing to realize is that the globals of __init__.py are
> also
> > the attribute namespace of the package.
> Do you think this is confusing for anyone?  It seems obvious to me,
> but I'm pretty familiar with the import system. :)

When you look at it from a different angle it's totally obvious. But
apparently it surprised Dave and Barry.

--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/import-sig/attachments/20150422/cc18ab22/attachment.html>

More information about the Import-SIG mailing list