Message from discussion
I thought I understood how import worked...
Received: by 10.180.72.205 with SMTP id f13mr1180767wiv.4.1344849501739;
Mon, 13 Aug 2012 02:18:21 -0700 (PDT)
MIME-Version: 1.0
Path: q11ni107067359wiw.1!nntp.google.com!feed-C.news.volia.net!volia.net!news2.volia.net!feed-A.news.volia.net!npeer.de.kpn-eurorings.net!npeer-ng0.de.kpn-eurorings.net!news-feed.eu.lambdanet.net!texta.sil.at!news.glorb.com!solaris.cc.vt.edu!news.vt.edu!newsfeed-00.mathworks.com!panix!roy
From: Roy Smith <r...@panix.com>
Newsgroups: comp.lang.python
Subject: I thought I understood how import worked...
Date: Tue, 07 Aug 2012 09:18:26 -0400
Organization: PANIX Public Access Internet and UNIX, NYC
Lines: 47
Message-ID: <roy-B56619.09182407082012@news.panix.com>
NNTP-Posting-Host: localhost
X-Trace: reader1.panix.com 1344345506 25328 127.0.0.1 (7 Aug 2012 13:18:26 GMT)
X-Complaints-To: abuse@panix.com
NNTP-Posting-Date: Tue, 7 Aug 2012 13:18:26 +0000 (UTC)
User-Agent: MT-NewsWatcher/3.5.3b3 (Intel Mac OS X)
I've been tracking down some weird import problems we've been having with
django. Our settings.py file is getting imported twice. It has some
non-idempotent code in it, and we blow up on the second import.
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. Here's a small-ish test case which
demonstrates what I'm talking about (python 2.6.5):
In directory /home/roy/play/import/foo, I've got:
__init__.py (empty file)
try.py
broken.py
$ cat broken.py
print __file__
$ cat try.py
import broken
import foo.broken
import sys
for m in sys.modules.items():
if m[0].endswith('broken'):
print m
And when I run try.py (with foo as the current directory):
$ PYTHONPATH=/home/roy/play/import python try.py
/home/roy/play/import/foo/broken.pyc
/home/roy/play/import/foo/broken.pyc
('broken', <module 'broken' from '/home/roy/play/import/foo/broken.pyc'>)
('foo.broken', <module 'foo.broken' from '/home/roy/play/import/foo/broken.pyc'>)
So, it appears that you *can* import a module twice, if you refer to it by
different names! This is surprising. It means that having non-idempotent code
which is executed at import time is a Bad Thing.
It also means that you could have multiple copies of a module's global
namespace, depending on how your users imported the module. Which is kind of
mind-blowing.