Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

python - Python3 correct way to import relative or absolute?

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
    layer/
        __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

  1. 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...