How to properly use relative or absolute imports in Python modules?

前端 未结 6 1477
我在风中等你
我在风中等你 2020-12-02 20:30

Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: ValueError: Att

6条回答
  •  时光取名叫无心
    2020-12-02 21:09

    You need __init__.py in each folder.

    Relative import works only when you do:

    python test.py
    

    test.py imports foo.py and foo.py can relative import anything from the folder of test.py and above.

    You can't do:

    cd foo
    python foo.py
    python bar.py
    

    It will never work.

    You can try the sys.path.append or sys.path.insert solution but you gonna screw up the paths and you'll have problems with the f=open(filename).

提交回复
热议问题