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

  1. Marks directory as package - Python knows it’s importable
  2. Runs on import - Code in __init__.py runs when package is imported
  3. 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