Modules and imports · 5 / 16 Theory

Packages and __init__.py

When a project grows, a single file is not enough, and neither is a folder full of loose modules. A package is a folder that groups related modules under one name.

What a package is

A folder with an __init__.py file is enough (it may be empty). That file runs the first time the package is imported and marks the folder as a package. The modules inside are imported with dots.

# Illustrative example: it needs real files, not run in the corrector.
my_project/
├── main.py
└── shop/              <- a PACKAGE (folder with modules)
    ├── __init__.py      <- runs when the package is imported
    ├── prices.py
    └── orders.py

The standard library is full of packages: os.path, json.decoder, xml.etree, email.mime…

import os.path
import json.decoder

print(os.path.basename("/a/b/report.txt"))        # report.txt
print(json.decoder.JSONDecodeError.__module__)     # json.decoder

Ways to import

Inside the project you use absolute imports (with the full package name) or relative imports (with dots, only inside a package).

# Illustrative example: it needs real files, not run in the corrector.
# main.py
import shop.prices                       # used as shop.prices.vat(10)
from shop import prices                  # used as prices.vat(10)
from shop.prices import vat              # used as vat(10)
from shop.prices import vat as tax  # with another name

# shop/orders.py  (RELATIVE imports, inside the same package)
from . import prices                       # "." = this package
from .prices import vat
from .. import other_package                 # ".." = the parent package

Prefer absolute imports in the main code; relative ones let the package be renamed or moved without touching its modules.

What to put in __init__.py

It is usually left empty or used as a facade: re-exporting the important names so that whoever uses the package does not need to know its internal structure.

# Illustrative example: it needs real files, not run in the corrector.
# shop/__init__.py
from .prices import vat, discount     # re-exports: "from shop import vat" works
__all__ = ["vat", "discount"]          # what is imported by "from shop import *"
__version__ = "1.0"

__all__ is the list of names imported by from package import *; even if it exists, avoid that import * in your code because it hides where each name comes from.

Importing without knowing the name in advance

With importlib.import_module("shop.prices") a module is imported from a text, which makes it possible to load plug-ins or choose modules according to configuration. You practice it in Dynamic import.