Relative imports in Python 3
How do relative imports work in Python 3, and what makes them different from absolute imports? Relative imports let you organize code within packages by importing modules relative to the current file’s location.
Relative imports in Python 3 are a way to import modules within the same package or directory structure without specifying the full absolute path. They are especially useful when you’re working on larger projects where modules are grouped inside packages, and you want a cleaner, more maintainable way to reference them.
In Python 3, relative imports use a dot (.) notation to indicate the current or parent directories:
- A single dot (.) means the current package.
- Two dots (..) mean the parent package.
- You can chain dots to move up multiple levels.
For example, if you have this structure:
project/
│── package/
│ ├── module_a.py
│ └── module_b.py
Inside module_b.py, you can write:
from . import module_a
or import a specific function:
from .module_a import my_function
Some key points about relative imports:
- Only work within packages: You can’t use relative imports in standalone scripts; the code must be part of a package.
- Avoids long paths: Keeps imports shorter and easier to maintain compared to absolute imports.
- Can cause confusion: If misused, especially with nested packages, it may be harder to read compared to absolute imports.
- Best practice: Use relative imports for internal modules of the same package, and absolute imports when referring to external modules or higher-level packages.
In short, relative imports in Python 3 help maintain cleaner and more modular code within packages. However, they should be used carefully to keep the codebase readable and less error-prone.