Python Modules, Packages and Environments · Lesson 112 of 149

Python Packages and __init__.py

What you will learn

  • What a package is, and the role of __init__.py
  • Absolute and relative imports
  • Sub-packages and the dotted names
  • Exporting a clean interface with __init__.py and __all__
  • Namespace packages (folders without __init__.py)
  • Running package modules correctly: python -m

1. From modules to packages

A single module is one file. A bigger program needs many modules, and they are grouped into packages: a package is a folder of modules, usually with a file called __init__.py. A package gives you a dotted name: shop.pricing means "the module pricing inside the package shop". You have already used packages from the standard library: os.path, json.decoder, xml.etree.ElementTree.

Here is the example used in this lesson:

project/
├── main.py
└── shop/
    ├── __init__.py
    ├── config.py
    ├── pricing.py
    └── tools/
        ├── __init__.py
        └── format.py

shop is a package, and shop.tools is a sub-package inside it.

2. What init.py does

When you import a package, Python runs its __init__.py once. That file:

  1. marks the folder as a regular package;
  2. can contain setup code, constants such as __version__, and imports that define the package's public interface;
  3. may be empty (and often is).

Here are the files. shop/config.py:

DIGITS = 2

shop/pricing.py:

from . import config


def total(prices, discount=0):
    return round(sum(prices) * (1 - discount), config.DIGITS)

shop/__init__.py:

"""The shop package."""
print("shop/__init__ runs")

from .pricing import total

__all__ = ["total"]
__version__ = "1.0"

and main.py:

import shop

print(shop.total([10, 20]), shop.__version__)
shop/__init__ runs
30 1.0

The print shows that importing shop executed __init__.py. Because __init__.py imported total from pricing, users can write the short shop.total(...) instead of shop.pricing.total(...). This is called re-exporting, and lets you design the package's public face while the files inside stay organised as you like.

Keep __init__.py light: heavy work there slows down every import of the package.

Quick check: when does the code in `shop/__init__.py` run?

Once, the first time anything in the package shop is imported.

3. Importing from a package

All of these work with the files above:

from shop import pricing, config
print(pricing.total([1.005, 2], 0.1), config.DIGITS)

from shop.tools.format import label
print(label([5, 5.5]))

import shop.tools.format as fmt
print(fmt.label([1]), fmt.__name__, fmt.__package__)
print(shop.__name__)
2.7 2
shop.tools/__init__ runs
Total: 10.50
Total: 1.00 shop.tools.format shop.tools
shop
  • from shop import pricing, config imports submodules as names.
  • from shop.tools.format import label follows the dotted path. The line shop.tools/__init__ runs appears because the sub-package shop.tools was imported for the first time.
  • import shop.tools.format as fmt binds the long name to a short one. A module's __package__ is the package it belongs to.
  • A package also has __path__ (the folder or folders it was found in) and __file__ (its __init__.py).

A missing name gives the usual ImportError:

from shop import missing
ImportError: cannot import name 'missing' from 'shop' (.../shop/__init__.py)

4. Absolute and relative imports

Inside a package, one module can import another in two ways:

Style Example (inside shop/pricing.py) Meaning
absolute from shop import config the full path from the top package
relative from . import config . means "the package this file is in"
relative from .config import DIGITS a name from the sibling module config
relative from ..pricing import total .. means "one package up" (used in shop/tools/format.py)

shop/tools/format.py uses both a parent-level and a same-level style:

from ..pricing import total
from .. import config


def label(prices):
    return f"Total: {total(prices):.{config.DIGITS}f}"

The number of dots counts the levels: one dot is the current package, two dots the parent. Relative imports keep working if you rename the top package, and make clear that a module belongs to the same package. Absolute imports are easier to read and are recommended by many style guides; use whichever your team prefers, but be consistent. Relative imports work only inside a package.

Running files inside a package

A relative import needs Python to know the file is part of a package. Running the file directly loses that knowledge:

$ python shop/pricing.py
ImportError: attempted relative import with no known parent package

Run it as a module of the package instead, from the project folder (project/):

$ python -m shop.pricing
shop/__init__ runs

This time no error: Python imported the package first, then ran pricing with a known parent. (The module itself prints nothing, since it only defines a function.) Likewise, starting Python inside the shop folder and importing pricing as a top-level module fails for the same reason. Always run your program from the project folder, with a top-level script like main.py or python -m package.

5. all and import *

__all__ is a list of names that from package import * should bring in (lesson 16.1 discourages star imports, but libraries still define __all__ to state their public names):

from shop import *

print(total([1, 2]))
pricing
3
NameError: name 'pricing' is not defined

Only total was imported, because shop.__all__ is ["total"]. Note that the submodule pricing is still available as shop.pricing (it was loaded when __init__ imported it), but not as a bare name here. A listing of the package's names shows what is available after the imports:

print(sorted(n for n in dir(shop) if not n.startswith("__")))
['config', 'pricing', 'tools', 'total']

Submodules appear as attributes once they have been imported.

6. Namespace packages

A folder without __init__.py can still be imported (since Python 3.3) as a namespace package:

import nopkg.helper

print(nopkg.helper.VALUE)
print(nopkg.__path__)
7
_NamespacePath(['.../nopkg'])

This is mainly for splitting one big package across several folders. For ordinary projects, add an __init__.py to every package folder: tools, test runners and readers all expect it, and the intent is clear.

7. Designing packages

Guideline Why
group modules by purpose (shop/pricing.py, shop/tools/) easy to find things
keep the package shallow (one or two levels) short imports
give each module one job small, testable files
expose the public names in __init__.py users do not need to know the file layout
avoid circular imports (lesson 16.2) move shared code into its own module
avoid code with side effects in __init__.py faster, safer imports

A package like this is the first step to a distributable project (lesson 19.5), which also adds files for installing it.

Worked example: the shop package in use

Everything in this lesson fits together in one small project. main.py (the only file you run) uses the package through its public interface, and the output shows the order in which the __init__.py files run:

import shop
print(shop.total([10, 20]), shop.__version__)

from shop import pricing, config
print(pricing.total([1.005, 2], 0.1), config.DIGITS)

from shop.tools.format import label
print(label([5, 5.5]))

import shop.tools.format as fmt
print(fmt.label([1]), fmt.__name__, fmt.__package__)
shop/__init__ runs
30 1.0
2.7 2
shop.tools/__init__ runs
Total: 10.50
Total: 1.00 shop.tools.format shop.tools
Line of output Explanation
shop/__init__ runs the first import shop ran the package's __init__.py
30 1.0 shop.total (re-exported) and shop.__version__
2.7 2 the sum 3.005 less 10 percent is 2.7045, rounded to config.DIGITS = 2 digits
shop.tools/__init__ runs the sub-package ran its __init__.py the first time it was needed
Total: 10.50 format.label used both a relative import of total and of config
shop.tools.format shop.tools the module's full name and its package

The prices are made up. Change DIGITS in config.py and every module that uses config.DIGITS changes together: a single place for a setting.

Common mistakes

  • Forgetting __init__.py and surprised by a namespace package (or by tools failing to find the package).
  • Running a module inside a package directly (python shop/pricing.py) and getting "attempted relative import with no known parent package". Use python -m shop.pricing from the project folder.
  • Starting Python inside the package folder.
  • Putting heavy code in __init__.py.
  • Using import * instead of an explicit interface.
  • Circular imports between package modules.
  • Naming a package or module like a standard one (shop/json.py is fine inside a package, but json.py at the top is not).

Key takeaways

  • A package is a folder of modules, normally with an __init__.py; dotted names such as shop.tools.format follow the folders.
  • __init__.py runs once when the package is first imported; use it for the public interface, __version__ and __all__.
  • Absolute imports (from shop import config) and relative imports (from . import config, from .. import config) both work inside a package.
  • Run package code from the project folder, with python -m package.module or a top-level script.
  • Folders without __init__.py are namespace packages; prefer adding the file.

Practice

1. What file turns a folder into a regular package?

Show answer

__init__.py (it may be empty).

2. In shop/tools/format.py, which import reaches shop/pricing.py?

Show answer

from ..pricing import total (two dots mean one package up), or absolutely from shop.pricing import total.

3. What does from . import config mean?

Show answer

Import the module config from the same package as the current file.

4. Why does python shop/pricing.py fail when pricing.py uses a relative import?

Show answer

Run directly, the file is the top-level script and has no parent package, so relative imports cannot work. Use python -m shop.pricing from the project folder.

5. What does __all__ = ["total"] control?

Show answer

Which names from shop import * imports (only total).

6. Why re-export total in shop/__init__.py?

Show answer

Users can write shop.total(...) without knowing which file defines it, so the file layout can change without breaking their code.