2015-02-08 75 views
3

我正在写一个python模块neuralnet。它在Python2中工作得很好,但在Python3中,导入失败。Python3正确的方式来导入相对或绝对?

这是我的代码结构。

neuralnet/ 
    __init__.py 
    train.py   # A wrapper to train (does not define new things) 
    neuralnet.py  # Defines the workhorse class neuralnet 
    layers/ 
     __init__.py 
     inlayer.py  # Defines input layer class 
     hiddenlayer.py 

application/   # A seperate application (not part of the package) 
    classify.py  # Imports the neuralnet class from neuralnet.py 

train.py需要导入neuralnet.py的neuralnet类。

neuralnet.py需要导入层/ inlayer.py等

这需要导入此模块(我喜欢相对导入。)

我有一个不同的应用程序(classify.py)。 我在哪里...

from neuralnet.neuralnet import neuralnet 

我试过几种方法导入。 要么我得到一个错误(大多晦涩像父不导入)

1)当运行train.py(这是neuralnet模块的一部分)

from . import layer # In file neuralnet.py 
SystemError: Parent module '' not loaded, cannot perform relative import 

或者

2)同时运行classify.py(它在模块之外)。

from layer.inlayers import input_layer # In file neuralnet.py 
ImportError: No module named 'layer' 

我的导入多年来在Python2中工作得非常好。我想知道Python3对我的期望是什么?我应该将train.py移到我的模块外面(技术上它不是模块的一部分)?请建议最佳做法。

感谢 拉克什

+1

按'net.py'你的意思是'neuralnet.py'?您的示例不包含名为'net.py'的文件。另外,如果train.py不是你的软件包的一部分,那么是的,你应该将它移出。 – BrenBarn 2015-02-08 23:46:58

回答

1

在Python 3,相对进口被禁止,见https://www.python.org/dev/peps/pep-0328/https://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax

The only acceptable syntax for relative imports is from .[module] import name. All import forms not starting with . are interpreted as absolute imports. (PEP 0328)

from .stuff import Stuff明确相对导入,你 “应该” 做只要有可能,尽可能使用,并且必须在Python 3中使用。请前往https://stackoverflow.com/a/12173406/145400以获取有关相关进口的更深入分析。

+0

不,那不行! 'from .layer.inlayers import'InputLayer' throws 'SystemError:父模块''未加载,无法执行相对导入' – 2015-02-10 03:17:46

+1

您真的应该先清理您的问题(它仍然指向net.py)。然后,确保你正在正确使用'__init __。py'。在那里,你指定一个包的公共接口。也就是说,在'neuralnet/__ init __。py'中,最好导入相关的所有内容,并通过'__all__'控制应该暴露给外部的内容。与你的图层包一样。神经网络软件包应该只从层中导入那些你明确公开在'layers/__ init __。py'中的实体。 – 2015-02-10 18:17:01