Python3导入相对还是绝对的正确方法?

2024-05-14 23:43:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python模块。在Python2中一切正常,但在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需要导入layers/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中很好地运了很多年。我想知道Python对我有什么期望?我是否应该将train.py移到模块外部(技术上它不是模块的一部分)?请提出最佳做法。

谢谢 拉凯什


Tags: 模块thefrompyimportlayerinitlayers
1条回答
网友
1楼 · 发布于 2024-05-14 23:43:26

在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来深入分析相对进口。

相关问题 更多 >

    热门问题