Re: Dabeaz's weird import discovery

Guido van Rossum <[email protected]> Wed, 22 Apr 2015 10:37:11 -0700
Newsgroups gmane.comp.python.import
Message-ID <CAP7+vJJ_-QY+SiFxB1Ag-dxs-RAXe5YO9Y41ez+WDk7XpdSO6g@mail.gmail.com>
On Wed, Apr 22, 2015 at 10:33 AM, Eric Snow <[email protected]>
wrote:

> On Wed, Apr 22, 2015 at 11:15 AM, Guido van Rossum <[email protected]>
> 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)

_______________________________________________
Import-SIG mailing list
[email protected]
https://mail.python.org/mailman/listinfo/import-sig