What’s file “__init__.py”?

Priesdelly
2 min readJul 27, 2024

--

The __init__.py file is a special Python file used to indicate that a directory is a Python package. It can be an empty file, but it can also execute the initialization code for the package or set the __all__ variable to define the public interface of the package.

Key Points About "__init__.py"

  1. Package Initialization:

When a directory contains a __init__.py file, Python treats it as a package. This allows you to import modules from that directory using the package syntax.

For example, if you have a directory structure like this:

my_package/
├── __init__.py
├── module1.py
└── module2.pypython

You can import module1 and module2 like this:

from my_package import module1
from my_package import module2

2. Initialization Code:

The __init__.py file can contain an initialization code that runs when the package is imported. This can be useful for setting up package-level variables, importing submodules, or performing other initialization tasks.

Example:

# my_package/__init__.py
print("Initializing my_package")

3. Defining the Public Interface:

You can use the __all__ variable in __init__.py to define the public interface of the package. This specifies which modules or attributes should be accessible when the package is imported using from package import *.

Example:

# my_package/__init__.py
__all__ = ['module1', 'module2']

Example Usage

Directory Structure

my_project/
├── my_package/
│ ├── __init__.py
│ ├── module1.py
│ └── module2.py
└── main.py

my_package/__init__.py

# my_package/__init__.py
__all__ = ['module1', 'module2']

# Optional initialization code
print("Initializing my_package")

my_package/module1.py

# my_package/module1.py
def hello():
return "Hello from module1"

my_package/module2.py

# my_package/module2.py
def world():
return "Hello from module2"

main.py

# main.py
from my_package import module1, module2

print(module1.hello())
print(module2.world())

Summary

  • Purpose: The __init__.py file marks a directory as a Python package and can contain initialization code.
  • Initialization: It can run code when the package is imported.
  • Public Interface: It can define the public interface of the package using the __all__ variable.
  • Namespace Packages: In Python 3.3 and later, it is not strictly required but still commonly used for compatibility and initialization.

By understanding the role of __init__.py, you can better organize your Python projects and manage package-level initialization and imports effectively.

Content by Generative AI

--

--