python的命名空间_导入Python命名空间包的问题

1586010002-jmsa.png

I am trying to use Python namespace packages concept to split my library across multiple directories. In general, it works, but I have a problem regarding importing names to projects package level.

My project structure is following:

d0D8r.png

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:

$ 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 "", line 1, in

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. Also, is there a solution that works for both Python2.7 and Python3.4 (other versions not required).

解决方案

Starting with Python 3.3, you can use PEP 420 -- Implicit Namespace Packages.

Basically, you would remove your __init__.py file in both repositories, and add:

setup(

...

packages=['coollibrary.{foomodule/barmodule}'],

namespace_packages=['coollibrary'],

...

)

to your setup.py.

Can't help you with Python 2.7 though...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值