Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module imported multiple times

Tags:

python

django

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

like image 541
Ivan Virabyan Avatar asked Feb 04 '11 10:02

Ivan Virabyan


2 Answers

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.

like image 193
Gintautas Miliauskas Avatar answered Sep 29 '22 05:09

Gintautas Miliauskas


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

like image 34
Will Moore Avatar answered Sep 29 '22 03:09

Will Moore