Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 BeginneršŸ”µ Advanced
Modules Import BasicsCreating ModulesImport StatementsRelative ImportsImport PathsPackages StructureNamespace PackagesPip & DependenciesModule Performance
Python/Modules Packages/Relative Imports

🧭 Relative Imports — Import Within Your Package

Relative imports let you import modules from the same package without specifying the full path. They're useful when organizing code into packages.


šŸŽÆ Understanding Relative Imports

A relative import references modules relative to the current module's location, not from the top-level Python path.

myproject/
ā”œā”€ā”€ main.py
└── utils/
    ā”œā”€ā”€ __init__.py
    ā”œā”€ā”€ helpers.py
    └── validators.py

In validators.py:

# Absolute import (not relative)
from utils.helpers import format_string

# Relative import (uses dot notation)
from .helpers import format_string

šŸ’” Relative Import Syntax

Python uses dots (`.`) to indicate relative position.

# One dot (.) = current package
from . import helpers          # Import helpers module from current package
from .helpers import format    # Import format function from helpers

# Two dots (..) = parent package
from .. import config          # Import from parent package
from ..utils import helpers    # Import from parent's utils

# Three dots (...) = grandparent package
from ... import settings

šŸ—ļø Package Structure with Relative Imports

ecommerce/
ā”œā”€ā”€ __init__.py
ā”œā”€ā”€ main.py
ā”œā”€ā”€ models/
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ product.py
│   └── user.py
ā”œā”€ā”€ utils/
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ validators.py
│   └── formatters.py
└── services/
    ā”œā”€ā”€ __init__.py
    └── order.py

In ecommerce/models/product.py:

# Relative import from same package
from . import user  # Import user module from models

# Or import specific class
from .user import User

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

In ecommerce/services/order.py:

# Import from sibling package
from ..models import Product, User  # Go up to ecommerce, then down to models

class Order:
    def __init__(self, user, items):
        self.user = user  # Expects User object
        self.items = items  # Expects list of Product objects

šŸŽØ Practical Examples

Example 1: Simple Package

calculator/
ā”œā”€ā”€ __init__.py
ā”œā”€ā”€ basic.py
└── advanced.py

In basic.py:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

In advanced.py (using relative import):

from .basic import add  # Import from sibling module

def average(numbers):
    return add(*numbers) / len(numbers)

def compound_percentage(principal, rate, years):
    total = principal
    for _ in range(years):
        total = add(total, total * rate / 100)
    return total

In __init__.py (expose public API):

from .basic import add, subtract
from .advanced import average

__all__ = ["add", "subtract", "average"]

Example 2: Hierarchical Package

webapp/
ā”œā”€ā”€ __init__.py
ā”œā”€ā”€ models/
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ user.py
│   └── post.py
└── views/
    ā”œā”€ā”€ __init__.py
    └── profile.py

In models/user.py:

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email

    def is_valid(self):
        return "@" in self.email

In views/profile.py (import from parent's sibling):

# Go up one level (..) to webapp, then down to models
from ..models import User

def render_profile(user_id):
    user = User("john_doe", "john@example.com")
    if user.is_valid():
        return f"Profile: {user.username}"
    return "Invalid user"

In models/__init__.py (expose models):

from .user import User
from .post import Post

__all__ = ["User", "Post"]

šŸ“¦ When to Use Relative vs Absolute Imports

# āœ… Use relative imports WITHIN packages
# In mypackage/submodule.py
from . import helpers
from .helpers import format_string

# āœ… Use absolute imports for installed packages
import numpy as np
import requests
from flask import Flask

# āœ… Use absolute imports from external packages
from mypackage.models import User

# āŒ Avoid mixing when possible
from . import helpers  # Relative - internal
from mypackage import models  # Absolute - same package (inconsistent)

šŸ”„ Package Initialization with Relative Imports

The `__init__.py` file often uses relative imports to organize the package's public API.

# Package: myapp/
# File: myapp/__init__.py

# Import and expose key classes/functions
from .models import User, Product
from .utils import format_date
from .services import UserService

# Define what gets imported with 'from myapp import *'
__all__ = [
    "User",
    "Product",
    "format_date",
    "UserService"
]
# Now users can do:
from myapp import User, Product
from myapp.services import UserService

šŸ’» Real-World Example: Django-like Structure

project/
ā”œā”€ā”€ manage.py
ā”œā”€ā”€ core/
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ models.py
│   ā”œā”€ā”€ views.py
│   └── utils.py
└── accounts/
    ā”œā”€ā”€ __init__.py
    ā”œā”€ā”€ models.py
    ā”œā”€ā”€ views.py
    └── forms.py

In project/accounts/forms.py:

# Import User model from core package
from ..core.models import User

class LoginForm:
    def validate_user(self, username, password):
        # Would validate user exists
        return True

In project/accounts/views.py:

# Import forms from same package
from .forms import LoginForm

# Import utilities from core package
from ..core.utils import hash_password

def login(username, password):
    form = LoginForm()
    if form.validate_user(username, password):
        hashed = hash_password(password)
        return {"status": "success"}

āš ļø Common Issues and Solutions

Issue 1: "attempted relative import in non-package"

# āŒ This fails - file not in a package
# standalone_script.py
from . import helpers  # Error!

# āœ… Solution - make it a package with __init__.py
# my_package/__init__.py (empty file)
# my_package/script.py
from . import helpers  # Works now!

Issue 2: Circular Imports

# āŒ models.py imports views, views imports models
# models.py
from .views import render_profile

# views.py
from .models import User  # Circular!

# āœ… Solution - import inside function
# models.py
class User:
    def display(self):
        from .views import render_profile  # Import when needed
        return render_profile(self)

šŸ”‘ Key Takeaways

  • āœ… Use `.` for current package, `..` for parent package
  • āœ… Relative imports only work inside packages (with __init__.py)
  • āœ… Use relative imports within a package for clarity
  • āœ… Use absolute imports for external packages and libraries
  • āœ… Organize package's __init__.py to expose public API
  • āœ… Avoid circular imports by importing inside functions if needed

Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

Ā© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn