Interview question
What is __init__.py used for in Python packages? Python packages में __init__.py किस लिए इस्तेमाल होती है?
Answer
__init__.py marks a directory as a Python package and runs automatically when the package is first imported. It can be empty, or used to control what's exposed, run setup code, or simplify import paths.
# myapp/utils/__init__.py
# Empty file - still makes 'utils' a valid package
# OR expose specific items directly at the package level
from .math_utils import add, subtract
from .string_utils import capitalize_words
# This allows shorter imports for users of the package:
# from myapp.utils import add (instead of myapp.utils.math_utils.add)
# Controlling 'from package import *' behavior
__all__ = ['add', 'subtract', 'capitalize_words']
# only these names are imported when someone does 'from myapp.utils import *'
# Package-level initialization code (runs once, on first import)
print('Initializing utils package')
DEFAULT_CONFIG = {'version': '1.0'}
# Usage from outside
from myapp.utils import add # works because __init__.py exposed it
print(add(2, 3)) # 5
# Without the re-export in __init__.py, you'd need the longer path:
# from myapp.utils.math_utils import add__init__.py directory को Python package बनाती है और package पहली बार import होने पर automatically चलती है। यह empty हो सकती है, या क्या expose हो, setup code, या imports simplify करने के लिए use हो सकती है।
# myapp/utils/__init__.py
# Empty file - फिर भी 'utils' valid package है
# या package level पर specific items expose करना
from .math_utils import add, subtract
from .string_utils import capitalize_words
# यह छोटे imports देता है:
# from myapp.utils import add
# 'from package import *' behavior control करना
__all__ = ['add', 'subtract', 'capitalize_words']
# Package-level initialization code
print('utils package initialize हो रहा है')
DEFAULT_CONFIG = {'version': '1.0'}
from myapp.utils import add
print(add(2, 3)) # 5Was this answer clear?