I don't think the modules are actually imported twice. The entry is just doubled;that's all<br><br><div class="gmail_quote">On 7 August 2012 18:48, Roy Smith <span dir="ltr"><<a href="mailto:roy@panix.com" target="_blank">roy@panix.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">I've been tracking down some weird import problems we've been having with<br>
django.  Our settings.py file is getting imported twice.  It has some<br>
non-idempotent code in it, and we blow up on the second import.<br>
<br>
I thought modules could not get imported twice.  The first time they get<br>
imported, they're cached, and the second import just gets you a reference to the<br>
original.  Playing around, however, I see that it's possible to import a module<br>
twice if you refer to it by different names.  Here's a small-ish test case which<br>
demonstrates what I'm talking about (python 2.6.5):<br>
<br>
In directory /home/roy/play/import/foo, I've got:<br>
<br>
__init__.py  (empty file)<br>
try.py<br>
broken.py<br>
<br>
<br>
$ cat broken.py<br>
print __file__<br>
<br>
<br>
$ cat try.py<br>
import broken<br>
import foo.broken<br>
<br>
import sys<br>
for m in sys.modules.items():<br>
    if m[0].endswith('broken'):<br>
        print m<br>
<br>
<br>
And when I run try.py (with foo as the current directory):<br>
<br>
$ PYTHONPATH=/home/roy/play/import python try.py<br>
/home/roy/play/import/foo/broken.pyc<br>
/home/roy/play/import/foo/broken.pyc<br>
('broken', <module 'broken' from '/home/roy/play/import/foo/broken.pyc'>)<br>
('foo.broken', <module 'foo.broken' from '/home/roy/play/import/foo/broken.pyc'>)<br>
<br>
<br>
So, it appears that you *can* import a module twice, if you refer to it by<br>
different names!  This is surprising.  It means that having non-idempotent code<br>
which is executed at import time is a Bad Thing.<br>
<br>
It also means that you could have multiple copies of a module's global<br>
namespace, depending on how your users imported the module.  Which is kind of<br>
mind-blowing.<br>
<span class="HOEnZb"><font color="#888888">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></span></blockquote></div><br>