Relative vs. Absolute Imports

Carson West

Packages and init.py

Relative vs. Absolute Imports

These notes cover the differences and best practices for using relative and absolute imports in Python.

Absolute Imports:

These imports specify the full path to a module from the root of your project. They are generally preferred for their clarity and avoid ambiguity.

import mypackage.moduleA
from mypackage.moduleB import functionB

Advantages:

Disadvantages:

Relative Imports:

These imports specify the module’s location relative to the current module’s location. They use a dot (.) to indicate the relative position.

from .moduleC import functionC  # Imports moduleC from the same directory
from ..moduleD import functionD # Imports moduleD from the parent directory

Advantages:

Disadvantages:

Best Practices:

Package Structure (Circular Imports)