What is __init__.py in Python?

🧩 What is __init__.py in Python?


πŸ“˜ Definition

  • __init__.py is a special Python file used to mark a folder as a Python package.
  • It tells Python: “This folder contains Python code you can import.

πŸ“¦ Where is it used?

It is placed inside a package folder like this:

mypackage/
β”œβ”€β”€ __init__.py
β”œβ”€β”€ add.py
β”œβ”€β”€ sub.py


βœ… Why __init__.py is Important

PurposeExplanation
Marks folder as a packageWithout it, Python may not treat the folder as a package.
Runs code when importedYou can put code in it that runs automatically.
Helps in organizing importsMakes it easy to control what’s imported.

βœ… Example 1: Simple Empty __init__.py

# __init__.py
# (can be empty)

Usage:

from mypackage import add
print(add.add(2, 3))  # Output: 5


βœ… Example 2: With Code in __init__.py

# __init__.py
print("Welcome to mypackage!")

def greet():
    print("Hello from the package!")

Usage:

import mypackage

mypackage.greet()

πŸ–¨ Output:

Welcome to mypackage!
Hello from the package!


βœ… Example 3: Control Imports

If you want only certain modules to be accessible:

# __init__.py
__all__ = ['add']

Now:

from mypackage import *
# Only add is available, not sub


πŸ” Summary

ItemMeaning
__init__.pyMakes folder a package
Can be emptyYes
Can have codeYes (runs on import)
Can control what to importYes with __all__

πŸ“ Practice Task

❓ Create a package with:

  • __init__.py (prints “Package loaded”)
  • calc.py (function to add numbers)
  • Then import and use it.

βœ… Answer:

Folder: tools/

➑️ __init__.py

print("Package loaded!")

➑️ calc.py

def add(a, b):
    return a + b

➑️ Main file:

from tools import calc
print(calc.add(4, 5))  # Output: 9


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *