Re: Dabeaz's weird import discovery
Eric Snow <[email protected]> Wed, 22 Apr 2015 12:24:42 -0600
| Newsgroups | gmane.comp.python.import |
|---|---|
| Message-ID | <CALFfu7CvWhknasXG-atFcq71KTybBqfVZ0nMrrP5EwLvrP9mnA@mail.gmail.com> |
On Wed, Apr 22, 2015 at 12:06 PM, Guido van Rossum <[email protected]> wrote: > On Wed, Apr 22, 2015 at 10:54 AM, Eric Snow <[email protected]> >> 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. :) -eric