π§© 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
Purpose | Explanation |
---|---|
Marks folder as a package | Without it, Python may not treat the folder as a package. |
Runs code when imported | You can put code in it that runs automatically. |
Helps in organizing imports | Makes 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
Item | Meaning |
---|---|
__init__.py | Makes folder a package |
Can be empty | Yes |
Can have code | Yes (runs on import) |
Can control what to import | Yes 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
Leave a Reply