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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github