tezvyn:

Python Packages: Grouping Modules with __init__.py

AI-drafted, machine-checkedSource: docs.python.orgbeginner
Python Packages: Grouping Modules with __init__.py

A Python package is a folder of modules treated as one unit. The `__init__.py` file marks the folder as a package and can run setup code. Use it to organize large codebases.

WHY IT EXISTS: When a program grows beyond a single file, you need a way to organize related code. Python's modules (.py files) are the first step, but packages provide the next level of hierarchy, allowing you to group related modules into a single logical namespace.

THE MENTAL MODEL: A package is a directory of modules. The __init__.py file is the directory's "entry point" for the Python interpreter. Its mere presence turns a regular directory into an importable package. Think of it as the bouncer at a club: it checks you in and tells you what's available inside.

HOW IT WORKS: When you write import my_package, Python searches for a directory named my_package that contains an __init__.py file. Upon finding it, Python executes the contents of __init__.py to initialize the package. This file can be empty, which is the simplest case. Or, it can contain Python code to set up package-level variables, automatically import key functions from its sub-modules to make them easier to access, or define a special list called __all__ to explicitly name what should be imported when a user runs from my_package import *.

WHEN TO USE IT: Use packages for any project with more than a few files. It's the standard way to structure libraries and applications. For example, a web application might have packages for api, database, and services to keep the code clean and maintainable.

WHEN NOT TO USE IT: For very small, single-purpose scripts, a single .py module is perfectly fine. Introducing a package structure can be overkill and add unnecessary complexity if your entire program fits comfortably in one file.

ONE CANONICAL EXAMPLE: Imagine a directory utils with two files: __init__.py and formatters.py. Inside formatters.py, you have a function format_date(). If the __init__.py file is empty, you must import the function using from utils.formatters import format_date. However, if you add from .formatters import format_date inside your __init__.py file, you create a shortcut. Now, users of your package can simply write from utils import format_date, making for a cleaner public API.

Read the original → docs.python.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.