Interview question
What is the difference between a module and a package in Python? Python में module और package में क्या अंतर है?
Answer
| Term | Definition |
|---|---|
| Module | A single .py file containing Python code (functions, classes, variables) |
| Package | A directory containing multiple modules, with an __init__.py file marking it as a package |
# math_utils.py - this file IS a module
def add(a, b):
return a + b
def subtract(a, b):
return a - b
# Using the module
import math_utils
print(math_utils.add(2, 3)) # 5
# Package structure example:
# myapp/
# __init__.py
# utils/
# __init__.py
# math_utils.py
# string_utils.py
# models/
# __init__.py
# user.py
# Importing from a package
from myapp.utils.math_utils import add
from myapp.models.user import User
# Since Python 3.3, __init__.py is technically optional for 'namespace packages',
# but explicit __init__.py is still recommended for regular packages
# for clarity and to control what gets exposed on import| Term | Definition |
|---|---|
| Module | Python code वाली एक .py file |
| Package | कई modules वाली directory, __init__.py के साथ |
# math_utils.py - यह file एक module है
def add(a, b):
return a + b
def subtract(a, b):
return a - b
import math_utils
print(math_utils.add(2, 3)) # 5
# Package structure उदाहरण:
# myapp/
# __init__.py
# utils/
# __init__.py
# math_utils.py
# models/
# __init__.py
# user.py
from myapp.utils.math_utils import add
from myapp.models.user import User
# Python 3.3 से __init__.py technically optional है, पर
# explicit __init__.py अभी भी recommend किया जाता हैWas this answer clear?