Last modified: May 10, 2025 By Alexander Williams
Python Relative Imports Guide
Python relative imports help organize large projects. They allow importing modules from the same package. This guide explains how to use them.
What Are Relative Imports?
Relative imports specify module locations relative to the current file. They use dots to indicate hierarchy levels. This keeps imports clean and maintainable.
For example, from .sibling import func
imports from the same directory. Learn more in our Python Import Statements Guide.
Relative Import Syntax
Relative imports use dot notation. One dot means current directory. Two dots mean parent directory.
# Import from same directory
from .module import function
# Import from parent directory
from ..parent_module import ClassName
# Import from sibling package
from ..sibling_package.module import helper
The from .module
syntax is crucial for relative imports. Always use it in package contexts.
Project Structure Example
Consider this project structure:
my_project/
├── __init__.py
├── main.py
└── package/
├── __init__.py
├── module1.py
└── subpackage/
├── __init__.py
└── module2.py
To import module1
from module2
, use:
# In module2.py
from ..module1 import some_function
Common Errors and Solutions
ImportError: attempted relative import occurs often. It usually means you're running a module as main.
To fix this, either:
- Run the module as part of the package
- Use absolute imports instead
For more on import errors, see our Python Import System Guide.
Best Practices
Follow these rules for clean imports:
- Use relative imports within packages
- Prefer absolute imports for top-level modules
- Keep import paths as short as possible
The importlib
module offers advanced import control. Check our Python Import Best Practices guide.
Practical Example
Here's a working example with output:
# package/module1.py
def greet():
return "Hello from module1"
# package/subpackage/module2.py
from ..module1 import greet
print(greet())
# Output when run from project root
Hello from module1
When to Avoid Relative Imports
Don't use relative imports in:
- Standalone scripts
- Top-level modules
- Cases where absolute imports are clearer
For script-specific imports, consider import as
aliasing from our Python Import As Guide.
Conclusion
Python relative imports help manage complex projects. They keep imports clean and maintainable. Always use them within packages and follow best practices.
Remember the dot syntax and common pitfalls. With practice, relative imports become second nature in Python development.