Zet - Why do we need init.py?
Why do we need init.py?
__init__.py tells Python that a directory is a package.
Without __init__.py
mydir/
main.py
mypackage/
config.py
import mypackage.config # Error!
# ImportError: attempted relative import with no known parent package
With __init__.py
mydir/
main.py
mypackage/
__init__.py # Makes it a package
config.py
import mypackage.config # Works!
What it does
- Marks directory as package - Python knows it’s importable
- Runs on import - Code in
__init__.pyruns when package is imported - Optional - Can be empty, or contain setup code
Modern Python (3.3+)
PEP 420 introduced namespace packages - __init__.py is optional for pure packages. But it’s still recommended for:
- Explicit clarity
- Running init code
- Compatibility with older tools
#python