Attempted Relative Import With No Known Parent Package

The ImportError: Attempted Relative Import With No Known Parent Package error occurs in Python when a relative import is attempted from a module that is not part of a package.

Relative imports are used in Python to import modules from the same package. A relative import, on the other hand, is not possible if the module is not part of a package. An absolute import must be used instead.

Python Error
Python Error

Here’s an example on how you might encounter this error:

# file: my_module.py
from . import myothermodule

If ‘my_module.py‘ is run as a standalone script, it will raise the following error:

ImportError: Attempted relative import with no known parent package

How to fix ImportError: Attempted Relative Import With No Known Parent Package Error?

To fix this error, you can either move the ‘my_module.py‘ into a package or use an absolute import instead:

# file: my_module.py
import myothermodule

Alternatively, if you want to use a relative import, you can create an init.py file in the same directory as my_module.py, which will turn that directory into a Python package.

Conclusion

The ImportError: Attempted Relative Import With No Known Parent Package error occurs in Python when a relative import is attempted from a module that is not part of a package.

To fix this error, you can either move the python file into a package or use an absolute import instead.

Inquiries

By the way, if you have any questions or suggestions about this python error tutorial, please feel free to comment below.

Leave a Comment