Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 603
Ram Rachum Avatar asked Oct 18 '09 19:10

Ram Rachum


2 Answers

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

like image 106
Lennart Regebro Avatar answered Oct 14 '22 07:10

Lennart Regebro


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

like image 44
Benjamin Peterson Avatar answered Oct 14 '22 08:10

Benjamin Peterson