Python导入冲突 [英] Python import conflict
问题描述
我最近构建了一个Python包,并通过Debian打包器安装了它.它已安装在我的系统上,因此我可以在其他项目中使用它.在我的新项目中,我与包文件夹具有相同的名称,即opal.我扫描了包括该网站在内的所有网页,并指出了所有要使用的内容:
I recently build a Python package and installed it via Debian packager. It is installed on my system so I can use it in other projects. In my new project I have the same name of a package folder, namely, opal. I scanned the web including this site and everything pointed towards using:
from __future__ import absolute_import
不幸的是,它无法解决问题,我怀疑我错过了一个细节.
Unfortunately, it couldn't resolve the problem, I suspect I am missing a detail.
我正在使用Python 2.7.3,这是我的项目文件夹结构:
I am using Python 2.7.3 and here are my project folder structures:
已安装的软件包结构:
- opal
__init__.py
core.py
新项目结构:
- opal
- __init__.py
- net.py
在新项目中,我无法做:
In the new project I cannot do:
from opal.core import OpalClient
我总是收到在opal
下找不到core
的错误!!!
I always get an error that core
is not found under opal
!!!
如果__future__
是解决方案,请给我一个例子.我尝试了几种方法,但总是会出错.对于如此简洁的语言,我发现这是一个尴尬的问题;)
If __future__
is the solution, can somebody provide me an example. I tried several ways and always got errors. I found this an awkward problem for such a neat language ;)
欢呼
推荐答案
Python会在没有其他帮助的情况下 not 合并名称空间.在找到另一个顶级opal
程序包之前的某个位置中,您有一个opal
顶级程序包.找到的第一个软件包将opal.net
作为包含的模块,但没有将opal.core
作为模块.
Python does not merge namespaces without additional help. You have a opal
top-level package in one place that is being found before the other top-level opal
package is found. That first package found has opal.net
as a contained module, but not the opal.core
module.
您需要使用 setuptools名称空间设置才能启用此行为;使用兼容setuptools
的setup.py
安装软件包,并让它为您注册和管理名称空间.
You'll need to use a setuptools namespace setup to enable this behaviour; install your packages with a setuptools
compliant setup.py
and let it register and manage namespaces for you.
如果您使用的是Python 3.3或更高版本,则可以使用新的 PEP 420名称空间支持,您将在其中保留顶级目录 empty ,以创建一个可以合并的命名空间.另请参阅 命名空间包 Python 3导入系统文档.
If you are using Python 3.3 or newer, you can use the new PEP 420 namespace support, where you'd leave the top-level directory (or directories) empty to create a namespace that can then be merged. Also see Namespace packages in the Python 3 import system documentation.
这篇关于Python导入冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!