开发者

Module imported multiple times

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 开发者_JAVA技巧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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜