W3docs

Relative imports in Python 3

Relative imports in Python 3 allow you to import modules or functions from other packages within your package hierarchy.

Relative imports in Python 3 allow you to import modules or functions from other packages within your package hierarchy. This is useful when you want to import a module or function that is located in a different package but still within your project.

To use relative imports, you need to use the from . import syntax. The number of dots before the import statement represents the number of package levels you need to go up to reach the desired module or function. For example, consider the following directory structure:

package1/
├── __init__.py
├── package2/
│   ├── __init__.py
│   └── module2.py
└── module1.py

If you want to import a module module2 located in package2 from module1, you would use the following syntax:

Relative imports in Python 3

from .package2 import module2

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

If you want to import a function function2 located in module2, you would use the following syntax:

Importing a function from a nested package

from .package2.module2 import function2

It is important to note that relative imports only work when the module is imported as part of a package, not when run directly as a script (e.g., python module1.py). Additionally, every directory in the hierarchy must contain an __init__.py file (which can be empty) for Python to recognize them as packages.