What is init.py for?

Better Stack Team
Updated on October 5, 2023

In Python, the __init__.py file is used to mark a directory as a Python package. It is used to initialize the package when it is imported.

The __init__.py file can contain code that will be executed when the package is imported, as well as function definitions and variable assignments. It is a good place to put any code that you want to run when the package is first imported.

For example, suppose you have a package called mypackage with the following structure:

 
mypackage/
    __init__.py
    module1.py
    module2.py
    ...

If you want to import module1 from mypackage, you can do so using the following import statement:

 
import mypackage.module1

When you run this import statement, Python will execute the code in __init__.py before it executes the import statement for module1. This can be useful if you want to do some initialization or setup before the other modules in the package are imported.

It is also possible to have multiple levels of packages, with __init__.py files at each level. For example:

 
mypackage/
    __init__.py
    subpackage1/
        __init__.py
        module1.py
        module2.py
        ...
    subpackage2/
        __init__.py
        module1.py
        module2.py
        ...

In this case, you would import a module from subpackage1 using the following import statement:

 
import mypackage.subpackage1.module1

Again, the code in the __init__.py files for mypackage and subpackage1 would be executed before the import statement for module1 is executed.