relative imports
Python 3
Python modules
import system
software development

Relative imports in Python 3

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Sure, here's a detailed article on relative imports in Python 3, using Markdown formatting:


In Python 3, module importation is an essential feature that facilitates code reusability and modulability. One of the import mechanisms involves using relative imports, which are quite different from the more common absolute imports. This article explores the concept of relative imports, offering a thorough understanding along with examples and technical insights.

Understanding Relative Imports

Relative imports in Python use dot notation to refer to the current and parent directories. They provide a way to import modules relative to the location of the current module. This can be beneficial when working with package structures, as it simplifies the module path, especially when the package is part of a larger application or is designed to be standalone.

Basic Syntax

The syntax for relative imports is based on the number of dots (.):

  • A single dot (.) refers to the current package.
  • Two dots (..) refer to the parent package.
  • Three dots (...) move two levels up, and so forth.

Example Package Structure

Consider the following package structure:

 
1mypackage/
2    __init__.py
3    module_a.py
4    subpackage/
5        __init__.py
6        module_b.py

Absolute vs. Relative Import

In module_b.py, you might want to import module_a.

  • Absolute Import: This involves specifying the full path of the module.
python
  from mypackage import module_a
  • Relative Import: This uses relative path notation.
python
  from .. import module_a

When to Use Relative Imports

Relative imports are often used when dealing with:

  • Package Refactoring: When reorganizing packages, relative imports can make it simpler to move modules without altering their import paths significantly.
  • Encapsulation: If a package is meant to be used as a standalone library, relative imports maintain the hierarchal scope within that package.

Limitations of Relative Imports

  1. Cannot be Used at the Top Level: Relative imports only work within packages. They cannot be executed from the top-level script directly because Python does not identify the script's containing directory as a package.
  2. Readability Issues: Too many levels of relative imports (e.g., from ....subpackage import module) can decrease code readability, making it less obvious where the modules are located.

Example: Relative Import in Use

Suppose module_b.py requires a function from module_a.py. Here’s how you’d implement it using relative imports:

python
1# Inside subpackage/module_b.py
2
3from ..module_a import some_function
4
5def call_function():
6    some_function()

Key Points

FeatureAbsolute ImportsRelative Imports
Path SpecificationFull module path (e.g., from mypackage import module_a)Dots for relative paths (e.g., from .. import module_a)
Ideal ForApplication-wide module access Clear and explicit 🌐Intra-package access Refactoring 📂
ReadabilityHigh, via explicit pathsCan be less readable with multiple dots
UsageApplications, large projects where hierarchy clarity is importantEncapsulated packages where module movement is common
LimitationsNone, except potentially cumbersome path notationNot usable in top-level scripts Decreased readability with multiple levels

Considerations for Python 2.x Users

As of Python 3, relative imports require explicit notation, which was different from Python 2.x, where implicit relative imports were allowed. In other words, in Python 3, import module_a in module_b.py would look for module_a in the system's sys.path, not mypackage. Always ensure the package structure is part of your PYTHONPATH or is otherwise correctly initialized.

Conclusion

Relative imports offer a convenient way to manage modules systematically within your package, especially beneficial during developmental changes like package restructuring and encapsulation. This concept is crucial for building modular and maintainable Python code, though it is essential to understand its limitations and potential impacts on readability. With an in-depth understanding and careful structuring, relative imports can greatly contribute to an efficient codebase.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.