Whenever you try to import your code from a different folder, you throw in an empty __init__.py. It has almost become a muscle memory for most Python developers — beginners or wizards. But do we really know __init__.py?
In this blog post, let’s dive into how __init__.py works and three ways a non-empty __init__.py helps us as Python developers.
What is __init__.py?
__init__.py is a Python file that tells the Python interpreter that the folder should be treated as a package.
Unlike compiled languages such as C & C++, where dependencies must be pre-compiled before being used, Python’s interpreter fetches your dependencies on the fly. To signal to Python that a folder contains code that will be used elsewhere is through __init__.py.
So, think of __init__.py as a gatekeeper. It turns your folder into an importable Python package.
But __init__.py is also more than that. When you create a class in Python, you will often need to create an __init__ function too. That would define how an object should be constructed and is the first thing to be executed when an object of the class is created. Similarly, __init__.py is the constructor of a Python package. It will get executed first whenever the package gets imported. An empty __init__.py means an empty __init__ constructor method for your Python package. It is fine, but it doesn’t mean we can’t do more with it.
Use __init__.py with Caution
Since __init__.py is the constructor of a Python package, we need to be cautious about where we put __init__.py.
If we have a folder named datetime where we have some custom utility functions for processing date format:
# ./datetime/utils.pydef increment_date(date: int, increment: int) -> int:
"""Increate timestamp by milliseconds"""
return date + increment
We then add a __init__.py so that we can import the code in our main.py: