[Import-SIG] Dabeaz's weird import discovery

Eric Snow ericsnowcurrently at gmail.com
Wed Apr 22 20:24:42 CEST 2015

On Wed, Apr 22, 2015 at 12:06 PM, Guido van Rossum <guido at python.org> wrote:
> On Wed, Apr 22, 2015 at 10:54 AM, Eric Snow <ericsnowcurrently at gmail.com>
>> I see what you're saying.  __name__ and sys.modules definitely need to
>> reflect the fully resolved name.  I just mean that for relative import
>> there is no need to bind the submodule to the parent, is there?
> But there *is* a reason. The submodule must still be an attribute of the
> parent package, because of the invariant that if you have sys.modules['foo']
> and sys.modules['foo.bar'], the latter must appear as the 'bar' attribute of
> the former. This is an invariant of module loading, and (I feel I'm
> repeating myself) the form of import used does not affect loading.

Right.  That invariant is the only reason the bahavior should apply to
relative imports.  I just hadn't considered that as a general
invariant until this conversation. :)

> There is another import rule that is relevant here; while `import foo.bar`
> requires that bar is a module, `from foo import bar` accepts bar as any
> attribute that exists in foo. The rule is then that after `import foo.bar`,
> if you later do `from foo import bar`, it will use the bar attribute, and
> that will be the bar submodule. (Unless foo's __import__.py messed around
> with it.)

Yep.  The code to support this ("fromlist") is some of Brett's
favorite. <wink>  I believe he describes it as "hell". :)

>> EIBTI.  That's not specific to relative
>> imports, but it does demonstrate the only case I can think of where
>> someone might be relying on this behavior of relative imports.  That's
>> why I think it was unintentional.
>> Regardless, there's nothing to be done at this point besides document
>> the behavior. :)
> I expect if we redesigned it from first principles we'd end up with the same
> rules in this case.

Fair enough. :)


More information about the Import-SIG mailing list