Python Mastery – From Basics to Brilliance / Modules & Packages

__init__.py

βš™οΈ __init__.py

__init__.py is a special Python file used inside a package.

It can be used to initialize the package and control what gets imported from it.

πŸ“¦ Example

my_package/
β”‚
β”œβ”€β”€ __init__.py
β”œβ”€β”€ calculator.py
└── greeting.py

Here, my_package is the package and __init__.py belongs to it.


πŸ”Ή Using __init__.py

Suppose calculator.py contains:

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

We can import it through the package:

from my_package.calculator import add

print(add(10, 5))

πŸ’‘ Important

In modern Python, a folder can work as a package without __init__.py (namespace packages).

However, __init__.py is still commonly used because it can:

  • Initialize package-level code

  • Expose selected functions/classes

  • Control package imports

⭐ Remember

πŸ“¦ Package
   β”‚
   β”œβ”€β”€ __init__.py  β†’ Package initialization
   β”œβ”€β”€ calculator.py
   └── greeting.py

__init__.py β†’ Special file associated with a Python package.