How can I create imports that always work?

前端 未结 4 1114
孤独总比滥情好
孤独总比滥情好 2021-01-27 23:08

I am struggling a bit to set up a working structure in one of my projects. The problem is, that I have main package and a subpackage in a structure like this (I left out all unn

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-27 23:31

    Unfortunately relative imports and direct running of submodules don't mix.

    Add the parent directory of mypackage to your PYTHONPATH or always cd into the parent directory when you want to run a submodule.

    Then you have two possibilities:

    Use absolute (from mypackage import utils) instead of relative imports (from . import utils) and run them directly as before. The drawback with that solution is that you'll always need to write the fully qualified path, making it more work to rename mypackage later, among other things.

    or

    Run python3 -m mypackage.utils etc. to run your submodules instead of running python3 mypackage/utils.py.

    This may take some time to adapt to, but it's the more correct way (a module in a package isn't the same as a standalone script) and you can continue to use relative imports.

    There are more "magical" solutions involving __package__ and sys.path but they all require extra code at the top of every file with relative imports you want to run directly. I wouldn't recommend these.

提交回复
热议问题