Relative import

Contents

Relative import#

This page discusses the implementation details of the relative imports in python.

__main__ module#

A common issue related to relative imports in Python occurs when attempting to execute a Python file that contains relative imports.

Check out this stackoverflow discussion of what actually happens.

Python uses the module’s __name__ attribute of the module when loading imports into the module. If the import occurs in the __main__ module, correct path to the module cannot be built, resulting in an ImportError. Running the module with the -m flag processes the path of the python interpreter a bit differently.


A few following cells create a simple project structure that uses relative imports.

%%bash
rm -rf /tmp/relative_import
mkdir -p /tmp/relative_import/package
%%writefile /tmp/relative_import/package/module1.py
print("module1")
Writing /tmp/relative_import/package/module1.py
%%writefile /tmp/relative_import/package/intro_module.py
from . import module1
Writing /tmp/relative_import/package/intro_module.py

The following cell attempts to run intro_module as the main programm’s main module.

!cd /tmp/relative_import/ && python3 package/intro_module.py
Traceback (most recent call last):
  File "/tmp/relative_import/package/intro_module.py", line 1, in <module>
    from . import module1
ImportError: attempted relative import with no known parent package

The result is the ImportError, which makes it clear that the error occurs due to relative import. The following cell runs package.intro_module with the -m flag. As a result, the programm executes without any problems.

!cd /tmp/relative_import/ && python3 -m package.intro_module
module1

Note: This won’t work if the module you want to run doesn’t have a parent package. The following cell demonstrates an attempt to run the intro_module from the package folder.

!cd /tmp/relative_import/package/ && python3 -m intro_module
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "/tmp/relative_import/package/intro_module.py", line 1, in <module>
    from . import module1
ImportError: attempted relative import with no known parent package