Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

What is __init__.py for?

Solution:

The __init__.py file in Python is used to identify a directory as a Python package. When a package is imported, it is used to start it.

The __init__.py file can include code that will run when the package is imported, in addition to function definitions and variable assignments. It's an ideal spot to put any code you want to run when importing the package.

Let’s take an example.

Imagine you have a package called mypackage.


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

And you want to import module 1 from mypackage. You can do so using this-


import mypackage.module1

When you run this import statement, Python will first run the code in __init__.py before running the import statement for module 1. It is handy if you want to conduct some initialization or setup before importing the other modules in the package. It is also possible to have many tiers of packages, each with its __init__.py file. 

Let’s see an example.


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

Here, for importing a module, you can use the subpackage1.


import mypackage.subpackage1.module1

Again, the code in mypackage and subpackage1's __init__.py files would be performed before the import statement for module1.

Follow MarsDevs blogs to learn more about such Python tricks!