Member-only story
Can You Even __init__.py?
Casting magic using __init__.py
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…