Open In App

Relative Import in Python

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, relative imports allow us to import modules in relation to the current module's location within a package structure. This means instead of using full paths, we can import modules using . (current directory) or .. (parent directory), making the code more concise and easier to maintain. Relative imports are especially useful in large projects with complex directory structures, where we want to keep module imports flexible and avoid hard-coding long paths. They help ensure that the code remains portable, as the module paths are relative to the package, not absolute locations on the filesystem.

Relative imports use dots (.) to indicate the current and parent directories:

  • . refers to the current directory.
  • . . refers to the parent directory.
  • . . . refers to the grandparent directory, and so on.

Example

Suppose we have the following package structure:

project_name/
├── main.py
└── package/
├── __init__.py
├── module_a.py
└── module_b.py
Contents of the Modules

module_a.py

Python
def greet(name):
    return f"Hello, {name}!"

module_b.py

Python
from .module_a import greet  # Relative Import

def farewell(name):
    return f"Goodbye, {name}!"

def use_greet_and_farewell(name):
    greeting = greet(name)
    goodbye = farewell(name)
    return f"{greeting} {goodbye}"

main.py

Python
from package.module_b import use_greet_and_farewell  # Absolute Import

if __name__ == "__main__":
    name = "GeeksforGeeks"
    message = use_greet_and_farewell(name)
    print(message)

Output:

Hello, GeeksforGeeks! Goodbye, GeeksforGeeks

How It Works

  1. Relative Import in module_b.py:
    • from .module_a import greet: This imports the greet function from module_a using a relative import (relative to module_b in the same directory).
  2. Absolute Import in main.py:
    • from package.module_b import use_greet_and_farewell: This imports the use_greet_and_farewell function from module_b using the full path (starting from the package root).
  3. Run the Program: Execute the main.py file from the root directory (project_name/) to run the project correctly:
python main.py

Next Article
Article Tags :
Practice Tags :

Similar Reads