I thought I understood how import worked...

Cameron Simpson cs at zip.com.au
Tue Aug 7 18:47:36 EDT 2012


On 07Aug2012 13:52, Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
| On Tue, 07 Aug 2012 09:18:26 -0400, Roy Smith wrote:
| > I thought modules could not get imported twice.  The first time they get
| > imported, they're cached, and the second import just gets you a
| > reference to the original.  Playing around, however, I see that it's
| > possible to import a module twice if you refer to it by different names.
| 
| Yes. You've found a Python gotcha.
[...]
| > $ cat try.py
| > import broken
| > import foo.broken
| 
| Which are two names for the same module.
[...]

This, I think, is a core issue in this misunderstanding. (I got bitten
by this too, maybe a year ago. My error, and I'm glad to have improved
my understanding.)

All of you are saying "two names for the same module", and variations
thereof. And that is why the doco confuses.

I would expect less confusion if the above example were described as
_two_ modules, with the same source code.

Make it clear that these are _two_ modules (because they have two
names), who merely happen to have been obtained from the same "physical"
filesystem object due to path search effects i.e. change the doco
wording to describe a module as the in-memory result of reading a "file"
found from an import name.

So I think I'm arguing for a small change in terminology in the doco
with no change in Python semantics. Is a module a set of files on the
disc, or an in-memory Python notion with a name? I would argue for the
latter.

With such a change, the "a module can't be imported twice" would then be
true (barring hacking around in sys.modules between imports).

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

As you can see, unraveling even a small part of 'sendmail' can introduce more
complexity than answers.        - Brian Costales, _sendmail_



More information about the Python-list mailing list