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.


FeatureDescription
PurposeMarks a directory as a Python package so it can be imported.
File NameMust be named __init__.py.
Optional SincePython 3.3 (namespace packages can exist without it).
Can Contain CodeYes β€” used for initialization code, imports, or package-level variables.
ExecutionRuns 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 + b

Usage:

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__.py defines 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.

Scroll to Top