我正在尝试使用 Python命名空间包概念将我的库拆分到多个目录中。一般来说,它可以工作,但我在将名称导入项目包级别时遇到问题。
我的项目结构如下:
project1/coollibrary/__init__.py
from __future__ import absolute_import
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from .foomodule import foo
project1/coollibrary/foomodule.py
def foo():
print ('foo')
project2/coollibrary/__init__.py
from __future__ import absolute_import
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from .barmodule import bar
project2/coollibrary/barmodule.py
def bar():
print ('bar')
这两个项目都在 PATH 中:
$ echo ${PYTHONPATH}
/home/timo/Desktop/example/project1:/home/timo/Desktop/example/project2
我正在从这里运行代码:
$ pwd
/home/timo/Desktop/example
$ python3
>>> import coollibrary
>>> coollibrary.foo() # works
foo
>>> coollibrary.bar() # does not work (the problem)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'bar'
>>> import coollibrary.barmodule
>>> coollibrary.barmodule.bar() # works
bar
如何修复代码,以便我可以直接从包中foo
导入。此外,是否有适用于 Python2.7 和 Python3.4 的解决方案(不需要其他版本)。bar
coollibrary