How to fix "Attempted relative import in non-package" even with __init__.py
The "Attempted relative import in non-package" error occurs when attempting to use a relative import within a script that is not part of a package. To fix this, you should make sure that the script is part of a package by creating an __init__.py
file in the directory containing the script.
Here is an example of how to fix the error in a file called module.py
that is located in the directory mypackage
:
# mypackage/__init__.py (create this file if it does not exist)
# mypackage/module.py
from . import another_module
Alternatively, you can use an absolute import instead of a relative import:
# mypackage/module.py
import mypackage.another_module
Note that in Python 3, __init__.py
file is no longer necessary to make a directory a package, however it is still recommended to use it.