What Does Python’s __init__.py Do?
Python’s special __init__.py file marks a directory as a regular Python package and allows you to import its modules. This file runs automatically the first time you import its containing package. You can use it to initialize package-level variables, define functions or classes, and structure the package’s namespace clearly for users.
By the end of this video course, you’ll understand that:
- A directory without an
__init__.pyfile becomes a namespace package, which behaves differently from a regular package and may cause slower imports. - You can use
__init__.pyto explicitly define a package’s public API by importing specific modules or functions into the package namespace. - The Python convention of using leading underscores helps indicate to users which objects are intended as non-public, although this convention can still be bypassed.
- Code inside
__init__.pyruns only once during the first import, even if you run the import statement multiple times.
Understanding how to effectively use __init__.py helps you structure your Python packages in a clear, maintainable way, improving usability and namespace management.
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]