I have a module named extended.py which contains the following line:
from .basic import BasicModule
and the file basic.py resides in the same directory as does __init__.py. However, when I try to run it as:
python extended.py
I get the error:
ValueError: Attempted relative import in non-package
Also adding the line:
from __future__ import absolute_import
does not solve the problem.
Maybe I am too tired to see the obvious – but I don’t see the problem here.
Relative imports only work for packages, but when you importing in
extended.pyyou are running a top-level module instead.The current directory may hold a
__init__.pyfile but that doesn’t makeexended.pypart of a package yet.For something to be considered a package, you need to import the directory name instead. The following would work:
then in
main.pyput:and only then is
extendedpart of a package and do relative imports work.The relative import now has something to be relative to, the
packagenameparent.