Python3 correct way to import relative or absolute?

ⅰ亾dé卋堺 提交于 2019-12-19 09:01:03

问题


I am writing a python module neuralnet. It was working all fine in Python2, but in Python3, imports are failing.

This is my code structure.

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 needs to import neuralnet.py's neuralnet class.

neuralnet.py needs to import layers/inlayer.py etc.

(I prefer relative imports.)

I have a different application (classify.py) which needs to import this module. Where I do...

from neuralnet.neuralnet import neuralnet

I have tried a few ways to import. Either I get an error (mostly arcane like parent is not imported)

1) While running train.py (which is a part of the neuralnet module)

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

Or

2) while running classify.py (which is outside the module).

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

My imports worked perfectly well for years in Python2. I am wondering what Python3 expects of me? Should I move train.py to outside my module (technically it is not a part of the module)? Please suggest best practice.

Thanks Rakesh


回答1:


In Python 3, implicit relative imports are forbidden, see https://www.python.org/dev/peps/pep-0328/ and 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 is an explicit relative import, which you "should" make use of whenever possible, and must use in Python 3, whenever possible. Head over to https://stackoverflow.com/a/12173406/145400 for a deeper analysis on relative imports.



来源:https://stackoverflow.com/questions/28400690/python3-correct-way-to-import-relative-or-absolute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!