Search⌘ K
AI Features

Packages and __init__.py

Explore how Python packages organize related modules using directories and the special __init__.py file. Understand how to use __init__.py for package initialization, creating clear public interfaces, employing relative imports, and controlling exports to maintain scalable, maintainable Python projects.

As applications grow, maintaining all code in a single file or a collection of loosely organized scripts becomes difficult to manage. Projects require a way to group related functionality, such as separating database access from user interfaces or mathematical utilities from reporting tools. Python addresses this problem using packages. A package is a directory containing modules that Python treats as a single importable unit. This structure supports hierarchical module organization while maintaining a clear public interface for other developers.

Anatomy of a package

A Python package maps directly to the file system. While a module is a single file (e.g., calculations.py), a package is a directory containing modules and a special file named __init__.py. This file tells Python that the directory contains importable Python code, not just random files. Imagine we are building a graphics library named pixel_art. We would ideally want to separate shape logic from color definitions.

Directory structure:

pixel_art/ <-- Top-level package directory
├── __init__.py <-- Marker file (makes this a package)
├── shapes.py <-- Submodule
└── colors.py <-- Submodule

In case you want to see the directory in the terminal, try using the ls command:

Terminal 1
Terminal
Loading...

First, we define logic inside the shapes module.

C++
# File: pixel_art/shapes.py
def draw_circle(radius):
return f"Drawing a circle with radius {radius}"
def draw_square(side):
return f"Drawing a square with side {side}"
  • Lines ...