Skip to content

Module 14 · Python Modules and Packages — topic 8 of 13

__init__.py

The role of __init__.py: marking a folder as a regular package, running package initialisation code, exposing a convenient public API, __all__ and __version__, and why submodules aren't imported automatically.

Beginner 8 min read·Lesson 216 of 306 in Python Programming

Learning objectives

  • Explain when __init__.py runs
  • Expose a package's public API from __init__.py
  • Know that submodules must be imported explicitly

Definition

__init__.py is a module that runs when its package is imported. It marks the folder as a regular package and can define package-level names, import submodules to build a convenient interface, and set __all__ and __version__.

Introduction

Users of your package shouldn't need to know your internal file layout. __init__.py lets them write geometry.circle_area instead of geometry.circle.area.

Why it matters

A well-designed __init__.py gives a package a clean front door and lets you reorganise internals without breaking users.

Detailed explanation

import package runs package/__init__.py once (and caches the package like any module). An empty file is perfectly fine.

Names defined or imported in __init__.py become attributes of the package: from .circle import area as circle_area makes package.circle_area available.

Importing a package does not automatically import its submodules. After import tools, tools.text exists only if __init__.py imports it or you import tools.text yourself.

__all__ in __init__.py controls from package import *.

__version__ = "1.2.0" is a common convention for exposing the package version.

Keep __init__.py light: heavy work there slows every import of the package and can cause circular-import problems.

Without __init__.py, a folder becomes a namespace package. That works, but regular packages with __init__.py are clearer for normal projects.

Syntax

Python
# geometry/__init__.py
from .circle import area as circle_area
from .square import area as square_area
__all__ = ["circle_area", "square_area"]
__version__ = "1.2.0"
  • Runs when the package is imported.
  • Re-export names for a clean API.
  • Keep it light.

Code examples

A package with a public API

Python
from pathlib import Path
import importlib
files = {
"geometry/__init__.py": '''print("initialising geometry")
from .circle import area as circle_area
from .square import area as square_area
__all__ = ["circle_area", "square_area"]
__version__ = "1.2.0"
''',
"geometry/circle.py": '''import math
def area(r):
return round(math.pi * r * r, 2)
''',
"geometry/square.py": '''def area(s):
return s * s
''',
}
for rel, src in files.items():
Path(rel).parent.mkdir(exist_ok=True)
Path(rel).write_text(src, encoding="utf-8")
importlib.invalidate_caches()
import geometry
import geometry # __init__.py runs only once
print(geometry.circle_area(1), geometry.square_area(3), geometry.__version__)
Output
initialising geometry
3.14 9 1.2.0

Submodules need importing

Python
from pathlib import Path
import importlib
Path("tools").mkdir()
Path("tools/__init__.py").write_text("", encoding="utf-8")
Path("tools/text.py").write_text('''def shout(s):
return s.upper() + "!"
''', encoding="utf-8")
importlib.invalidate_caches()
import tools
print(hasattr(tools, "text"))
import tools.text
print(hasattr(tools, "text"), tools.text.shout("hi"))
Output
False
True HI!

More examples

A dispatching package interface

Python
from pathlib import Path
import importlib
files = {
"reports/__init__.py": '''from .csv_report import to_csv
from .text_report import to_text
__all__ = ["to_csv", "to_text"]
FORMATS = {"csv": to_csv, "text": to_text}
def render(rows, fmt="text"):
try:
return FORMATS[fmt](rows)
except KeyError:
raise ValueError(f"unknown format {fmt!r}; choose from {sorted(FORMATS)}") from None
''',
"reports/csv_report.py": '''def to_csv(rows):
return " / ".join(",".join(map(str, r)) for r in rows)
''',
"reports/text_report.py": '''def to_text(rows):
return " / ".join(" ".join(f"[{v}]" for v in r) for r in rows)
''',
}
for rel, src in files.items():
Path(rel).parent.mkdir(exist_ok=True)
Path(rel).write_text(src, encoding="utf-8")
importlib.invalidate_caches()
import reports
rows = [("pen", 20), ("bag", 1200)]
print(reports.render(rows, "csv"))
print(reports.render(rows))
try:
reports.render(rows, "pdf")
except ValueError as e:
print(e)
from reports import *
print(sorted(n for n in dir() if n.startswith("to_")))
Output
pen,20 / bag,1200
[pen] [20] / [bag] [1200]
unknown format 'pdf'; choose from ['csv', 'text']
['to_csv', 'to_text']

Step-by-step explanation

  • __init__.py imports the two format functions and builds a FORMATS table.
  • Users call reports.render without knowing which file implements each format.
  • from reports import * brings in exactly the names listed in __all__.

Expected output

Running “A dispatching package interface” prints exactly:

TextOutput
pen,20 / bag,1200
[pen] [20] / [bag] [1200]
unknown format 'pdf'; choose from ['csv', 'text']
['to_csv', 'to_text']

Practical applications

  • requests/__init__.py re-exports get, post and Session.
  • Packages exposing __version__ for tools and bug reports.

Best practices

  • Re-export the public API from __init__.py.
  • Define __all__ and __version__.
  • Keep __init__.py fast and free of side effects.

Common mistakes

Expecting automatic submodule import

Avoid

import tools
tools.text.shout("hi") # AttributeError

Prefer

import tools.text
tools.text.shout("hi")

Submodules load only when imported (by you or by __init__.py).

Heavy initialisation

Avoid

# __init__.py
DATA = load_big_dataset()

Prefer

def load_data():
return load_big_dataset()

Every import of the package would pay the cost.

Important notes

  • Use relative imports (from .module import name) inside __init__.py.

Key takeaways

  • __init__.py runs when the package is imported.
  • It can re-export names for a clean API.
  • Submodules aren't imported automatically.

Try it yourself

  1. 1
    Create a units package whose __init__.py exposes km_to_miles and kg_to_lb from two submodules.
  2. 2
    Add __version__ to a package and print it from a script.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateAfter import shop, why might shop.pricing raise AttributeError?
Practise this topic