The __init__.py file is a special Python file used to mark a directory as a Python package.
When a directory contains this file, Python treats it as a package, allowing you to import modules from that directory.
| Feature | Description |
|---|---|
| Purpose | Marks a directory as a Python package so it can be imported. |
| File Name | Must be named __init__.py. |
| Optional Since | Python 3.3 (namespace packages can exist without it). |
| Can Contain Code | Yes β used for initialization code, imports, or package-level variables. |
| Execution | Runs automatically when the package or any module inside it is imported. |
π§© Example 1: Basic Package Structure
my_package/
β
βββ __init__.py
βββ module1.py
βββ module2.py# module1.py
def greet():
print("Hello from module1")
# __init__.py
print("Initializing my_package")Usage:
import my_package.module1
my_package.module1.greet()Output:
Initializing my_package
Hello from module1π§© Example 2: Importing Functions in __init__.py
# __init__.py
from .module1 import greet
from .module2 import add
# module1.py
def greet():
print("Hello, Dheeraj!")
# module2.py
def add(a, b):
return a + bUsage:
from my_package import greet, add
greet()
print(add(5, 10))Output:
Hello, Dheeraj!
15π§© Example 3: Package Initialization Code
# __init__.py
print("Package is being initialized...")
config = {"version": "1.0", "author": "Dheeraj"}Usage:
import my_package
print(my_package.config)Output:
Package is being initialized...
{'version': '1.0', 'author': 'Dheeraj'}In Summary:
__init__.pydefines a package and allows imports from it.- It can contain initialization logic, shared variables, or shortcut imports.
- From Python 3.3 onward, itβs optional, but still commonly used for explicit package control and clean imports.
