如何避免在Python模块系统中命名冲突?

问题描述:

在我的Django项目中,我有一个名为profile的应用程序,它主要包含我的profile.models.UserProfile类,以获取有关User对象(Django人可能看起来很熟悉)的其他信息。现在我已将一些初始化代码放入profile/__init__.py(某些信号),并且遇到了一个问题:Django告诉我一个名为hotshot_profile的表尚未找到。如何避免在Python模块系统中命名冲突?

经过几个小时的搜索后,我将问题追溯到导入顺序。运行python -v manage.py test我发现以下几点:

import nose.plugins.prof # precompiled from /home/rassie/.virtualenvs/myproject/lib/python2.6/site-packages/nose/plugins/prof.pyc 
import hotshot # directory /usr/lib64/python2.6/hotshot 
import hotshot # precompiled from /usr/lib64/python2.6/hotshot/__init__.pyc 
dlopen("/home/rassie/.virtualenvs/myproject/lib64/python2.6/lib-dynload/_hotshot.so", 2); 
import _hotshot # dynamically loaded from /home/rassie/.virtualenvs/myproject/lib64/python2.6/lib-dynload/_hotshot.so 
import hotshot.stats # from /usr/lib64/python2.6/hotshot/stats.py 
import profile # directory /home/rassie/MyProject/apps/profile 
import profile # precompiled from /home/rassie/MyProject/apps/profile/__init__.pyc 

所以我的鼻子流道进口nose.plugins.prof(即使这个插件是关闭的),进口hotshot,它试图导入profile。但是,profile导入我的项目,而它准备好应该从系统Python导入。

显然,我自己的profile模块与系统profile模块冲突。我显然不能从我自己的编程中排除与Python捆绑在一起的每个模块名称。所以问题是,我从哪里出发?我是否必须为我的所有应用程序创建myproject命名空间? Django会使用它吗?

PS:表名hotshot_profile似乎来自于一个Profilepybb,我也在我的项目中使用的进一步尚未完全分析的命名冲突。但是这不在这个问题的范围之内。

您不应该以import mymodule(相对导入)的形式导入您自己的模块。相反,您应该始终使用import myproject.mymodule(绝对导入)。这可以避免所有名称冲突。

+1

我一直以为我已经使用绝对导入按照我能找到的每个Django的建议。看来我需要将我的应用程序放入一个名称空间,然后放到全局路径中,并按照您的说法导入它们。我们会看看这是否顺利:) –