2017-08-19 23 views
0

我想从我的子模块导入一个类,而不必使用from submodule.submodule import Class语法。相反,我只想像from submodule import Class一样正常的Python3模块。干净地导入自定义模块

我觉得这应该已经回答了一百万次,虽然在SO上有几个类似命名的问题,但没有一个提供了一个简单的解决方案,只有一个简单的例子。

我试图让最简单的测试与此设置工作:

. 
├── main.py 
└── test 
    ├── __init__.py 
    └── test.py 

在我test模块,我有以下内容:

test.py

class Test: 
    def __init__(self): 
     print('hello') 

__init__.py

from test import Test 
__all__ = ['Test'] 

在上级main.py我有以下几点:

from test import Test 
Test() 

当我尝试运行main.py我得到:

ImportError: cannot import name 'Test' 

我知道我可以代替导入语句main.pyfrom test.test import Test,但我的理解是__init__.py的要点之一是使子模块可以在包中访问GE水平(与__all__允许导入所有from test import *

回答

1

根据PEP 404

在Python 3,包内隐相对进口不再 可用 - 只有绝对的进口和明确的相对进口 支持的。另外,明星进口(例如从x进口*)在模块级代码中仅允许 。

如果更改__init__.py到:

from test.test import Test 
__all__ = ['Test'] 

那么你的代码工作:

$ python3 main.py 
hello 

但现在它仅适用于python3(和你原来的代码仅适用于python2)。
背负上蟒的两条线运行的代码,我们必须使用明确的相对进口

from .test import Test 
__all__ = ['Test'] 

代码执行:

$ python2 main.py 
hello 
$ python3 main.py 
hello