the full guide

Packages

A package is a folder of modules that can be imported together. A file named __init__.py marks it as a regular package, and can set up what the package exposes. Modules inside can import each other using relative imports.

8 min Intermediate

What you need: The earlier topics of this module.

Definition

A package is a folder of modules that can be imported together. A file named __init__.py marks it as a regular package, and can set up what the package exposes. Modules inside can import each other using relative imports.

In simple words

If modules are chapters, a package is the book. import shop.billing means: open the shop folder, then the billing file.

Why it matters

Beyond a few files, you need folders. NumPy, scikit-learn and PyTorch are all packages, and knowing the layout helps you read their code and errors.

How it works

shop/
    __init__.py          # marks the package
    billing.py           # def total(items): ...
    inventory/
        __init__.py
        stock.py

import shop.billing
from shop.billing import total
from shop.inventory.stock import count

# inside shop/inventory/stock.py
from ..billing import total     # relative: up one folder, then billing

Common mistakes

  • Running a file inside a package directly when it uses relative imports. Use python -m.
  • Putting heavy work in __init__.py, which slows every import.

Check yourself

Question 1

1. What marks a folder as a regular package?

Question 2

2. In from ..billing import total, what do the two dots mean?

Summary

  • A package is a folder of modules.
  • __init__.py marks it and sets up its contents.
  • Run packaged files with python -m.

Finished reading?

Sources: The Python Tutorial, python.org