python – How to fix Attempted relative import in non-package even with __init__.py
python – How to fix Attempted relative import in non-package even with __init__.py
To elaborate on Ignacio Vazquez-Abramss answer:
The Python import mechanism works relative to the __name__
of the current file. When you execute a file directly, it doesnt have its usual name, but has __main__
as its name instead. So relative imports dont work.
You can, as Igancio suggested, execute it using the -m
option. If you have a part of your package that is meant to be run as a script, you can also use the __package__
attribute to tell that file what name its supposed to have in the package hierarchy.
See http://www.python.org/dev/peps/pep-0366/ for details.
Yes. Youre not using it as a package.
python -m pkg.tests.core_test
python – How to fix Attempted relative import in non-package even with __init__.py
You can use import components.core
directly if you append the current directory to sys.path
:
if __name__ == __main__ and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))