How to accomplish relative import in python

前端 未结 6 1253
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 10:38
stuff/
    __init__.py
    mylib.py
    Foo/
        __init__.py
        main.py
        foo/
            __init__.py
            script.py

s

6条回答
  •  执念已碎
    2020-12-01 11:25

    If you're on Linux or perhaps a similar *nix, you can hack this with symlinks.

    stuff/
        mylib.py
        foo.py // equivalent of main.py in above
        foo/
            script.py
            mylib.py  ->  ../mylib.py
        foo2/
            script2.py
            mylib.py  ->  ../mylib.py
    
    

    This is likely not a good pattern to follow.

    In my case I opted for it because I had multiple executables dependent on the same library that needed to be put into separate directories.

    Implementation of new executable tests shouldn't require the test writer to have a deep understanding of python imports.

    tests/
        common/
            commonlib.py
        test1/
            executable1.py
            executable2.py
            commonlib.py -> ../common/commonlib.py
        test2/
            executable1.py
            executable2.py
            commonlib.py -> ../common/commonlib.py
    
    
    

提交回复
热议问题