ImportError: attempted relative import with no known parent package
Fixes ImportError: attempted relative import with no known parent package Use when running a module file directly that contains `from .` / `from ..` imports Not for: absolute imports failing (that is ModuleNotFoundError, different fix)
How to fix ImportError: attempted relative import with no known parent package
You ran a file that uses relative imports (from . import x) directly as a script, so Python does not know its package. Run it as a module from the project root: python -m package.module instead of python package/module.py. Or convert the relative imports to absolute ones.
The exact error
ImportError: attempted relative import with no known parent packageFix it
From the project root (where the top package dir lives), run
python -m package.module. Expected: relative imports resolveAlternative: rewrite
from .helpers import fasfrom package.helpers import f. Expected: works however it is launchedCheck every package dir has an init.py (namespace packages aside). Expected: package structure recognized
When this applies
running a module file directly that contains from . / from .. imports
When this does NOT apply
absolute imports failing (that is ModuleNotFoundError, different fix)
Versions
any Python 3
Why it happens
Relative imports need the module's package context; direct script execution leaves package unset.
Edge cases
python -m adds the CWD to sys.path; running from the wrong directory still fails.