When trying relative imports like from .mymodule import myfunction in Python 3, I sometimes see errors such as “attempted relative import with no known parent package” or “ModuleNotFoundError.”
Why does this happen, and how should relative imports be handled properly?
Hey @Asheenaraghununan
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.
When I saw “attempted relative import with no known parent package,” I realized it happens if you run a module as a standalone script that uses relative imports.
Relative imports depend on the module being inside a package. The solution I use is either switch to absolute imports or execute the module using the -m
option so Python knows the package structure.
Avoid running files with relative imports directly via python filename.py.
Hey @akanshasrivastava.1121 and @joe-elmoufak
This error comes up because Python’s relative imports only work if the module is part of a recognized package, and the script is run as a module, not a standalone file.
I always recommend structuring your project as packages and using python -m to run modules.
For example:
python -m mypackage.mymodule
This tells Python about the parent package and avoids “attempted relative import with no known parent package.” Otherwise, the interpreter won’t know where the relative import fits