开发者

Python: Do relative imports mean you can't execute a subpackage by itself?

开发者 https://www.devze.com 2022-12-09 07:34 出处:网络
I\'ve recently ported my Python project to run on Python 3.1. For that I had to adopt the policy of relative imports within the submodules and subpackages of my project. I\'ve don’t that and now the

I've recently ported my Python project to run on Python 3.1. For that I had to adopt the policy of relative imports within the submodules and subpackages of my project. I've don’t that and now the project itself works, but I noticed I can't execute any of the subpackages or submodules in it. If I try, I 开发者_运维问答get "builtins.ValueError: Attempted relative import in non-package". I can only import the whole project.

Is this normal?


Yes, it's normal. If you want to execute a module that is also a part of a package (in itself a strange thing to do) you need to have absolute imports. When you execute the module it is not, from the interpreters point of view, a part of a package, but the __main__ module. So it wouldn't know where the relative packages are.

The standard way to do it is to have functions in the packages, and separate executable scripts that call the functions, as this enables you to put the executable scripts outside the module, for example in /usr/bin


You can use -m flag of the python interpreter to run modules in sub-packages (or even packages in 3.1.).


I had the same problem and I considered the -m switch too hard.

Instead I use this:

try:
    from . import bar
except ValueError:
    import bar

if __name__ == "__main__":
    pass
0

精彩评论

暂无评论...
验证码 换一张
取 消