What is __init__.py file in Python

Pratik Choudhari

This article explains why the __init__.py file exists in Python packages.

There are two types of packages in python, regular and namespace packages. The former requires __init__.py file whereas the latter does not. Any directory with an init python file is marked as a package by python and can be imported.

Whenever a package is imported using the import keyword or the from x import y syntax the init file is run implicitly. Generally, this file is kept empty but it can be used to achieve the following things:

Working with __init__.py file

First, let's create a directory named my_package and add a new file __init__.py with this content

print("my_package is imported")

With this setup, we can now test if my_package can be imported using the following script

import my_package

Output:

my_package is imported

As we can see, as soon as my_package was imported the init file was run. Similarly, several submodules can be created with their own __init__.py file. For example

my_package/ ├── __init__.py ├── sub_package_1 │ └── __init__.py ├── sub_package_2 │ └── __init__.py └── sub_package_3 └── __init__.py 3 directories, 4 files

Similar content is written into all init files as in the my_package init file. We can then import all submodules

from my_package import sub_package_1, sub_package_2, sub_package_3

Output:

my_package is imported sub_package_1 is imported sub_package_2 is imported sub_package_3 is imported

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses