I faced the “attempted relative import with no known parent package” error when I tried running a script directly that used relative imports like from .mymodul
e import myfunction.
This happens because Python needs to know your script is part of a package to resolve relative imports, and running a file directly doesn’t set that context.
To fix it, I started running the script using the -m
flag from the parent directory, like:
python -m package.subpackage.myscript
This way, Python treats it as a package module and resolves the relative imports correctly.