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.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With