
Python
Relative imports let you import modules from the same package without specifying the full path. They're useful when organizing code into packages.
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.pyIn validators.py:
# Absolute import (not relative)
from utils.helpers import format_string
# Relative import (uses dot notation)
from .helpers import format_stringPython 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 settingsecommerce/
āāā __init__.py
āāā main.py
āāā models/
ā āāā __init__.py
ā āāā product.py
ā āāā user.py
āāā utils/
ā āāā __init__.py
ā āāā validators.py
ā āāā formatters.py
āāā services/
āāā __init__.py
āāā order.pyIn 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 = priceIn 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 objectsExample 1: Simple Package
calculator/
āāā __init__.py
āāā basic.py
āāā advanced.pyIn basic.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - bIn 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 totalIn __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.pyIn models/user.py:
class User:
def __init__(self, username, email):
self.username = username
self.email = email
def is_valid(self):
return "@" in self.emailIn 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"]# ā
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)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 UserServiceproject/
āāā manage.py
āāā core/
ā āāā __init__.py
ā āāā models.py
ā āāā views.py
ā āāā utils.py
āāā accounts/
āāā __init__.py
āāā models.py
āāā views.py
āāā forms.pyIn 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 TrueIn 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"}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)Ready to practice? Challenges | Quiz
Resources
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