Interview question
What is the difference between absolute imports and relative imports in Python? Python में absolute imports और relative imports में क्या अंतर है?
Answer
| Type | Syntax | Based on |
|---|---|---|
| Absolute import | from myapp.utils import helper | Full path from the project root |
| Relative import | from .utils import helper / from ..models import User | Position relative to the current module |
# Project structure:
# myapp/
# __init__.py
# main.py
# utils/
# __init__.py
# helpers.py
# models/
# __init__.py
# user.py
# ABSOLUTE import (in models/user.py) - full path from project root
from myapp.utils.helpers import format_name
# RELATIVE import (in models/user.py) - relative to current module's location
from ..utils.helpers import format_name # .. means 'go up one package level'
from . import validators # . means 'current package'
# Single dot (.) = current package
# Double dot (..) = parent package
# Triple dot (...) = grandparent package, and so on
# Absolute imports are generally PREFERRED because they're:
# - explicit and unambiguous about where something comes from
# - easier to understand when reading code out of context
# - don't break as easily when files are moved within the package
# Relative imports are useful for:
# - large packages where the full path is long and repetitive
# - keeping a package portable/renamable without updating every import
# IMPORTANT: relative imports only work inside a package (won't work
# if you run the file directly as a script, only when imported as a module)| Type | Syntax | आधार |
|---|---|---|
| Absolute import | from myapp.utils import helper | Project root से पूरा path |
| Relative import | from .utils import helper | Current module के relative position |
# Project structure:
# myapp/
# utils/
# helpers.py
# models/
# user.py
# ABSOLUTE import (models/user.py में)
from myapp.utils.helpers import format_name
# RELATIVE import (models/user.py में)
from ..utils.helpers import format_name # .. = एक level ऊपर
from . import validators # . = current package
# Single dot = current package
# Double dot = parent package
# Absolute imports आमतौर पर बेहतर हैं क्योंकि:
# - explicit और स्पष्ट हैं
# - context के बिना पढ़ने में आसान
# - files move होने पर कम टूटते हैं
# ज़रूरी: relative imports सिर्फ package के अंदर काम करते हैंWas this answer clear?