__init__.py in Python: What It Is and How It Works
__init__.py is a special Python file used to mark a directory as a package so Python can import modules from it. It can be empty or contain initialization code that runs when the package is imported.How It Works
Imagine you have a folder full of Python files, and you want Python to treat that folder like a single unit called a package. The __init__.py file acts like a sign on the folder that says, "Hey, I'm a package!" Without this file, Python might not recognize the folder as a package, especially in older Python versions.
When you import a package, Python runs the code inside __init__.py first. This lets you set up things like variables, functions, or import other modules automatically. Think of it like opening a toolbox and arranging the tools neatly before you start working.
Example
This example shows a package folder with an __init__.py file that prints a message when the package is imported.
## Folder structure: # mypackage/ # __init__.py # module.py # Content of __init__.py print("mypackage is imported") # Content of module.py def greet(): return "Hello from module!" # Usage in another file or interactive shell import mypackage from mypackage import module print(module.greet())
When to Use
Use __init__.py whenever you want Python to treat a folder as a package. This is essential for organizing your code into reusable parts. You can leave it empty if you just want to mark the folder as a package, or add setup code to run on import.
Real-world uses include creating libraries, grouping related modules, or setting up package-level variables and imports to simplify access for users.
Key Points
__init__.pymarks a directory as a Python package.- It can be empty or contain initialization code.
- Code inside runs when the package is imported.
- It helps organize and reuse code in projects.
- In Python 3.3+, implicit namespace packages can work without it, but
__init__.pyis still widely used.
Key Takeaways
__init__.py tells Python a folder is a package.