5

I do some init stuff when a module is first loaded. The problem is that somehow it is imported twice, and I can't figure out why. I thought it might be imported using different path, as in this example:

a.py:

from apps.blog import models
...

b.py:

from blog import models
...

I insert print __name__ in my module, and it printed out blog.models twice, so it turnes out that the problem is not within import paths.
So, is there any other reason for a module to be imported multiple times?

UPDATE: I didn't mention that I'm using django. I think this problem related to django's manage.py script: https://docs.djangoproject.com/en/dev/releases/1.4/#updated-default-project-layout-and-manage-py

Ivan Virabyan
  • 1,666
  • 2
  • 19
  • 25
  • For anyone else who might have had this error, I found mine was caused by attempting to import from parent folders, not using `..` but by using `sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))` – Aesthete Aug 07 '12 at 01:16
  • Does this answer your question? [module reimported if imported from different path](https://stackoverflow.com/questions/1459236/module-reimported-if-imported-from-different-path) – Artyer Aug 12 '22 at 21:53

2 Answers2

10

Normally Python should not import a module twice regardless of absolute/relative references. It's likely that Python is seeing the source file as two different files and thus importing them separately. This could happen because of symlinked files/directories, or side-by-side different versions, or overlapping directories in PYTHONPATH, it's hard to say.

One way to track this down is to use the interactive debugger. Add a line import pdb; pdb.set_trace() in the top level of your file, and in the interactive shell enter bt to get a backtrace which should show the import chain. Continue with c. When the file is imported a second time and the debugger is activated, try bt again and compare the two outputs, that may reveal the problem.

Gintautas Miliauskas
  • 7,744
  • 4
  • 32
  • 34
2

Here is a very nice discussion of the multiple imports of settings.py in Django http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html

Will Moore
  • 552
  • 5
  • 11