简体   繁体   English

Python名称空间包的导入问题

[英]Import problems with Python namespace packages

I am trying to use Python namespace packages concept to split my library across multiple directories. 我正在尝试使用Python 名称空间包概念将我的库拆分到多个目录中。 In general, it works, but I have a problem regarding importing names to projects package level. 通常,它可以工作,但是在将名称导入到项目包级别时遇到问题。

My project structure is following: 我的项目结构如下:

示例项目结构

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')

Both projects are in the PATH: 这两个项目都在PATH中:

$ echo ${PYTHONPATH}
/home/timo/Desktop/example/project1:/home/timo/Desktop/example/project2

And I am running code from here: 我从这里运行代码:

$ 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

How to fix the code so that I could import both foo and bar directly from coollibrary package. 如何修复代码,以便可以直接从coollibrary包中导入foobar Also, is there a solution that works for both Python2.7 and Python3.4 (other versions not required). 另外,有没有一种适用于Python2.7和Python3.4(不需要其他版本)的解决方案。

Starting with Python 3.3, you can use PEP 420 -- Implicit Namespace Packages . 从Python 3.3开始,您可以使用PEP 420-隐式命名空间包

Basically, you would remove your __init__.py file in both repositories, and add: 基本上,您将在两个存储库中都删除__init__.py文件,并添加:

setup(
    ...
    packages=['coollibrary.{foomodule/barmodule}'],
    namespace_packages=['coollibrary'],
    ...
)

to your setup.py . 到您的setup.py

Can't help you with Python 2.7 though... 虽然无法帮助您使用Python 2.7 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM