Show contents
Chapter 2 of 7 · 20 min
Environment, dependencies, tests and logs
By the end of this chapter, you'll be able to
- Create a virtual environment and install dependencies into it
- Describe a project and its dependencies in pyproject.toml
- Organise pytest tests with fixtures and parametrisation
- Replace debugging prints with the logging module
One environment per project
A virtual environment is a folder that contains its own copy of Python and its own packages. Each project has its own: installing a library for one project doesn't break the others.
$ python -m venv .venv # creates the environment in the .venv folder
$ source .venv/bin/activate # activates it (Windows: .venv\Scripts\activate)
(.venv) $ pip install -e ".[dev]" # installs the project and its development tools
(.venv) $ pytest # runs the tests
The .venv folder is never shared: you add it to .gitignore. What you share is the description of the dependencies.
pyproject.toml: the project's identity card
The pyproject.toml file, in TOML format, describes the project: name, version, required Python version, dependencies. Python can read it with the tomllib module:
import tomllib
pyproject = """
[project]
name = "stock-manager"
version = "0.3.0"
requires-python = ">=3.12"
dependencies = ["httpx>=0.27"]
[project.optional-dependencies]
dev = ["pytest>=8", "mypy>=1.10"]
"""
config = tomllib.loads(pyproject)
project = config["project"]
print(project["name"], project["version"])
print("Dependencies:", project["dependencies"])
print("Dev tools:", project["optional-dependencies"]["dev"])
stock-manager 0.3.0
Dependencies: ['httpx>=0.27']
Dev tools: ['pytest>=8', 'mypy>=1.10']
A classic folder layout, called the src layout:
stock-manager/
├── pyproject.toml
├── src/stock_manager/
│ ├── __init__.py
│ ├── domain.py
│ └── service.py
└── tests/
├── conftest.py
└── test_service.py
The code lives in src/, the tests next to it. The tests therefore import the installed package, exactly as its users would.
pytest: fixtures and parametrisation
You already know test_… functions with assert. Two pytest tools avoid repetition:
# tests/test_service.py
import pytest
from stock_manager.service import Stock, Product
@pytest.fixture
def stock():
"""A brand-new stock for each test that asks for it."""
s = Stock()
s.add(Product("RICE", "Rice 1 kg", 1.2, 10))
return s
def test_sale(stock):
stock.sell("RICE", 3)
assert stock.quantity("RICE") == 7
@pytest.mark.parametrize("quantity", [0, -1, 11])
def test_invalid_sale_refused(stock, quantity):
with pytest.raises(ValueError):
stock.sell("RICE", quantity)
- a fixture prepares data; pytest automatically passes it to the tests that have a parameter of the same name, and creates a new one for each test;
@pytest.mark.parametrizeruns the same test with several values: here, three separate tests in the report;pytest.raises(ValueError)checks that an error is really raised.
logging rather than print
The logging module sorts messages by level (DEBUG, INFO, WARNING, ERROR, CRITICAL) and lets you choose, without touching the code, what is displayed and where:
import logging
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)-7s %(name)s: %(message)s", stream=sys.stdout, force=True)
log = logging.getLogger("payments")
def pay(amount: float) -> bool:
log.debug("checking the amount %s", amount)
if amount <= 0:
log.warning("amount refused: %s", amount)
return False
log.info("payment of %.2f accepted", amount)
return True
pay(25)
pay(-3)
log.setLevel(logging.DEBUG)
pay(10)
INFO payments: payment of 25.00 accepted
WARNING payments: amount refused: -3
DEBUG payments: checking the amount 10
INFO payments: payment of 10.00 accepted
- at the
INFOlevel,DEBUGmessages are ignored; you turn them on to investigate, without changing the code; getLogger("payments")creates a named log: each module has its own, and you set their levels separately;- you pass the values as arguments (
"… %s", amount) rather than with an f-string: the text is only built if the message is actually displayed.
The message is laid out according to the chosen format.
Text description of the animation
- The code emits a DEBUG-level message.
- The logger is set to INFO: the DEBUG message is dropped, at almost no cost.
- After setLevel(DEBUG), the same message gets through the filter.
- The handler chooses the destination: here the console, in production often a file or a service.
- The message is laid out according to the chosen format.
Your turn
Worked exercise
Worked exercise: a useful log
Rewrite this import function so that it uses a logger named import, instead of print. The number of lines read is an INFO message, each skipped line a WARNING giving its number, and the detail of each valid line a DEBUG. Configure logging at the INFO level, to standard output, in the format LEVEL name: message.
def import_lines(lines):
print("importing", len(lines), "lines")
result = []
for i, line in enumerate(lines, start=1):
if ";" not in line:
print("line skipped", i)
continue
print("line ok", line)
result.append(line.split(";"))
return result
Hint 1
logging.basicConfig(..., stream=sys.stdout, force=True) sets the output; force=True replaces an existing configuration.Hint 2
log.warning("line %d skipped", i).Show the solution and common mistakes
import logging
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s", stream=sys.stdout, force=True)
log = logging.getLogger("import")
def import_lines(lines):
log.info("importing %d lines", len(lines))
result = []
for i, line in enumerate(lines, start=1):
if ";" not in line:
log.warning("line %d skipped: %r", i, line)
continue
log.debug("line %d: %s", i, line)
result.append(line.split(";"))
return result
print(import_lines(["Ama;Accra", "empty line", "Bao;Hanoi"]))
INFO import: importing 3 lines
WARNING import: line 2 skipped: 'empty line'
[['Ama', 'Accra'], ['Bao', 'Hanoi']]
DEBUG messages don't appear at the INFO level. To see them, just write logging.getLogger("import").setLevel(logging.DEBUG), without touching the function.
Common mistakes:
- Logging everything as
INFO: in production, the important messages get lost among the details. - Building the message with an f-string (
log.debug(f"line {line}")): the text is built even when the message is ignored, which is costly in a loop over millions of lines.
Summary
- 1One virtual environment per project isolates its dependencies; .venv isn't shared.
- 2pyproject.toml describes the project, its Python version and its dependencies.
- 3pytest fixtures prepare fresh data; parametrize multiplies the cases.
- 4logging sorts messages by level and is configured without changing the code.
- 5Pass values as arguments to the logger rather than in an f-string.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.