Understand Python __init__.py for Beginners – Python Tutorial

By | October 21, 2019

Python __init__.py file will be run when importing a python model. In this tutorial, we will discuss the basic feature of __init__.py file for python beginners, you can learn how to use it correctly.

Why use __init__.py file

If there is a __init__.py file in a folder, which means this folder is a python model. __init__.py will be run when i import this model.

Here is an example.

understand python __init__.py file

The content of each file is:

mod_1_1.py : print("import mod_1_1")

mod_1_2.py : print("import mod_1_2")

mod_2_1.py : print("import mod_2_1")

mod_2_2.py : print("import mod_2_2")

Condition 1: No __init__.py  file in package_1 and package_2

To import from mod_1_1 to mod_2_2, we can add code in amod-test.py:

import package_1.mod_1_1
import package_1.mod_1_2

from package_2 import mod_2_1
from package_2 import mod_2_2

Run amod-test.py, we will get:

import mod_1_1
import mod_1_2
import mod_2_1
import mod_2_2

You will find all 4 python models are imported. However, if there are many models in each folder? Import each model is not a good choice, we will use __init__.py to fix this problem.

Condition 2: add __init__.py file in package_1 folder

Add a __init__.py file in package_1 folder, then add code below in this file.

print("run __init_py in package_1")

Then change code in amod-test.py to:

from package_1 import *

Run amod-test.py, you will get result like:

run __init_py in package_1

From result you will find, __init__.py in package_1 is run when importimg models. However, no models are importend.

Edit code in __init__.py in package_1 to:

print("run __init_py in package_1")
import mod_1_1
import mod_1_2

Run amod-test.py again, you will see result:

run __init_py in package_1
Traceback (most recent call last):
  File "E:\workspace-nlp\Example\amod-test.py", line 2, in <module>
    from package_1 import *
  File "E:\workspace-nlp\Example\package_1\__init__.py", line 4, in <module>
    import mod_1_1
ImportError: No module named 'mod_1_1'

We will find an error, beacuase we have not add package name when we are importing models in package_1.

Edit code in __init__.py again.

print("run __init_py in package_1")
import package_1.mod_1_1
from package_1 import mod_1_2

Run amod-test.py, we will get result like this:

run __init_py in package_1
import mod_1_1
import mod_1_2

From the result, we will see modes ‘mod_1_1‘ and ‘mod_1_2‘ are imported successfully in package_1.

Meanwhile, we also can use __all__ to simplify the process of importing python models.

Edit code in __init__.py to:

print("run __init_py in package_1")
__all__ = ['mod_1_1', 'mod_1_2']

Run amod-test.py again, we will see result like:

run __init_py in package_1
import mod_1_1
import mod_1_2

mod_1_1 and mod_1_2 are also imported successfully.

 

Leave a Reply

Your email address will not be published. Required fields are marked *