0
0
Pythonprogramming~5 mins

__init__ file role in Python

Choose your learning style9 modes available
Introduction

The __init__.py file tells Python that a folder is a package. It helps organize code into groups.

When you want to group related Python files into one package.
When you want to import code from one folder easily.
When you want to run setup code automatically when a package is imported.
When you want to control what is available when someone imports your package.
Syntax
Python
# __init__.py can be empty or contain code

# Example: initialize a variable
message = 'Hello from package'

# Example: import submodules
from . import module1
from . import module2

The __init__.py file must be inside the folder you want to treat as a package.

It can be empty or have Python code that runs when the package is imported.

Examples
This makes Python treat the folder as a package without extra setup.
Python
# Empty __init__.py file
# Just create an empty file named __init__.py inside the folder
This variable can be accessed when the package is imported.
Python
# __init__.py with a variable
message = 'Welcome to my package!'
This lets you import submodules directly from the package.
Python
# __init__.py importing submodules
from . import tools
from . import helpers
Sample Program

This example shows how __init__.py imports a function from a submodule so you can call it directly from the package.

Python
# Folder structure:
# mypackage/
#   __init__.py
#   greet.py

# Content of greet.py:
# def say_hello():
#     print('Hello from greet module!')

# Content of __init__.py:
from .greet import say_hello

# main.py (outside mypackage folder):
import mypackage

mypackage.say_hello()
OutputSuccess
Important Notes

Without __init__.py, Python 3.3+ treats folders as implicit namespaces, but explicit __init__.py is still recommended for clarity.

You can put setup code in __init__.py that runs when the package is imported.

Summary

__init__.py marks a folder as a Python package.

It can be empty or contain code to run on import.

It helps organize and control package imports.