Skip to content

13. Pythonic code

Code that works is not the end of the job. Other people read your code, and so do you, three months later. This module teaches you to write Python that reads like Python: short, direct and hard to get wrong. Every example is a real data task: sensor readings, customer records, price columns and monthly sales extracts.

  • Replace index loops and manual bookkeeping with Python idioms: enumerate, zip, dict.get, setdefault, comprehensions, unpacking, any/all, sum with a generator, f-strings, pathlib and with.
  • Choose between EAFP (“try it and handle the error”) and LBYL (“check first”) when you parse messy data.
  • Apply the PEP 8 essentials: names, layout, imports and comparisons.
  • Lint and format code with ruff, read its rule codes and apply its automatic fixes.
  • Recognize and fix five classic gotchas: mutable default arguments, late-binding closures, is versus ==, float precision and changing a list while you iterate over it.
  • Refactor a messy data script in small steps, with a check that proves the output did not change.

Code is Pythonic when it uses the features of Python the way the language intends. An idiom is a common, accepted way to express one small idea in a language. For example, for reading in readings: is the Python idiom for “visit every reading”. The version with for i in range(len(readings)): and readings[i] also works, but it adds an index that the task does not need.

Pythonic code matters for three reasons:

  1. Fewer bugs. Each extra index, counter or flag is one more thing that can be wrong. Idioms remove them.
  2. Faster reading. A reader recognizes an idiom at a glance, the way you recognize a word without reading each letter.
  3. Shared style. Python developers read the same idioms everywhere: in pandas, in web frameworks, in scripts. Your code fits in.

The Zen of Python is a list of 19 short design rules for Python, written by Tim Peters. The statement import this prints it. These lines guide this module:

import contextlib
import io
buffer = io.StringIO()
with contextlib.redirect_stdout(buffer):
import this # prints the Zen of Python when it is imported
zen = buffer.getvalue().splitlines()
for line in [zen[3], zen[4], zen[8], zen[11], zen[12], zen[14]]:
print(line)
Output
Explicit is better than implicit.
Simple is better than complex.
Readability counts.
Errors should never pass silently.
Unless explicitly silenced.
There should be one-- and preferably only one --obvious way to do it.

The code catches the printed text in a buffer so that it can show only six of the lines. In the REPL, import this is enough.

Pythonic does not mean “as short as possible”. A one-line comprehension with three nested loops is short but hard to read. The goal is code that is clear to the next reader.

Loop idioms: iterate directly, enumerate, zip

Section titled “Loop idioms: iterate directly, enumerate, zip”

A for loop in Python visits the items of an iterable directly. You rarely need an index. When you do need one, enumerate() gives it. When you walk two sequences side by side, zip() pairs them.

Instead of Write Why
for i in range(len(temps)): then temps[i] for temp in temps: no index to get wrong
a counter i = 0 … i += 1 for i, temp in enumerate(temps, start=1): the count cannot drift
for i in range(len(ids)): then ids[i], temps[i] for sensor_id, temp in zip(ids, temps): pairs stay together
for i in range(len(temps) - 1, -1, -1): for temp in reversed(temps): says what it means
for key in d: then d[key] for key, value in d.items(): one lookup, clear names

Here is a typical non-Pythonic loop and its Pythonic version. Both print the same lines.

sensor_ids = ["S1", "S2", "S3", "S4"]
temps = [20.21, 22.3, 19.4, 24.52]
for i in range(len(sensor_ids)):
print(str(i + 1) + ". " + sensor_ids[i] + ": " + str(temps[i]))
Output
1. S1: 20.21
2. S2: 22.3
3. S3: 19.4
4. S4: 24.52
for number, (sensor_id, temp) in enumerate(zip(sensor_ids, temps), start=1):
print(f"{number}. {sensor_id}: {temp}")
Output
1. S1: 20.21
2. S2: 22.3
3. S3: 19.4
4. S4: 24.52

zip() builds the pairs ("S1", 20.21), ("S2", 22.3) and so on. enumerate(..., start=1) numbers them from 1. The parentheses in (sensor_id, temp) unpack each pair. The nolint flag on the first block tells this course’s checker that the bad style is on purpose.

By default, zip() stops at the end of the shortest input and drops the rest without a word. Two columns of different lengths usually mean a bug upstream. Pass strict=True to make zip() raise an error instead:

temps_short = [20.21, 22.3, 19.4] # one reading was lost
for sensor_id, temp in zip(sensor_ids, temps_short, strict=True):
print(sensor_id, temp)
Output
S1 20.21
S2 22.3
S3 19.4
ValueError: zip() argument 2 is shorter than argument 1

The loop prints three pairs and then raises a ValueError, because the fourth sensor has no reading. Without strict=True, the loop would end after S3 and you would never know.

Dictionary idioms: get, setdefault, in, items

Section titled “Dictionary idioms: get, setdefault, in, items”

Data work counts and groups things all the time: rows per status, readings per sensor, revenue per region. Dicts do this job. Four idioms keep the code short and safe.

Task Idiom Result
read a key that may be missing config.get("timeout", 30) the value, or 30
count counts[k] = counts.get(k, 0) + 1 one more for k
group groups.setdefault(k, []).append(v) v added to the list of k
test for a key if "phone" in record: True or False
merge settings (later wins) settings = defaults | overrides a new dict
build a dict from pairs {k: v for k, v in pairs} a new dict

d.get(key, default) returns default when the key is missing, so it never raises a KeyError. d.setdefault(key, default) returns d[key], and first inserts default if the key is new. So groups.setdefault(k, []).append(v) creates the list the first time and reuses it after that.

statuses = ["ok", "ok", "warn", "ok", "fail", "warn", "ok"]
counts: dict[str, int] = {}
for status in statuses:
counts[status] = counts.get(status, 0) + 1
print(counts)
by_sensor: dict[str, list[float]] = {}
for sensor_id, temp in [("S1", 20.21), ("S2", 22.3), ("S1", 20.4), ("S2", 22.1)]:
by_sensor.setdefault(sensor_id, []).append(temp)
print(by_sensor)
defaults = {"interval_minutes": 10, "unit": "C"}
overrides = {"unit": "F"}
print(defaults | overrides)
Output
{'ok': 4, 'warn': 2, 'fail': 1}
{'S1': [20.21, 20.4], 'S2': [22.3, 22.1]}
{'interval_minutes': 10, 'unit': 'F'}

The standard library has two specialized dicts for the same jobs (module 09): collections.Counter counts, and collections.defaultdict(list) groups. Use them when counting or grouping is the main job of the code. Use get and setdefault for a quick count inside other code.

from collections import Counter
print(Counter(statuses).most_common(2))
Output
[('ok', 4), ('warn', 2)]

A comprehension builds a new list, dict or set from an iterable in one expression (module 04). A generator expression has the same syntax in parentheses. It produces the values one at a time instead of building a list (module 10). You can pass a generator expression straight to a function that consumes an iterable, such as sum(), min(), max(), any(), all() or str.join(). Then the extra parentheses can go.

temps = [20.21, 22.3, 19.4, 24.52, 38.03, 21.7]
hot = [t for t in temps if t > 30] # list comprehension
print(hot)
print(sum(t > 22 for t in temps)) # count: True counts as 1
print(max(t for t in temps if t < 30)) # largest normal reading
print(any(t > 35 for t in temps), all(t > 15 for t in temps))
Output
[38.03]
3
24.52
True True
  • sum(t > 22 for t in temps) counts the readings above 22, because True counts as 1 and False as 0.
  • any() is True when at least one value is truthy. It stops at the first truthy value, so it does not read the rest. all() stops at the first falsy value. This early stop is short-circuit evaluation (module 03).
  • A generator expression never builds the full list. For a file with millions of lines, sum(float(line) for line in f) uses almost no memory.

One edge case catches validation code. any() of an empty iterable is False, and all() of an empty iterable is True:

temps_today: list[float] = [] # the file for today was empty
print(all(t < 45 for t in temps_today))
print(any(t >= 45 for t in temps_today))
Output
True
False

“Every reading is below 45” is true for zero readings. Logicians call this vacuous truth: a rule about all members of an empty group is true because no member breaks it. A data check such as all(...) passes on an empty file. Check the count too: temps_today and all(t < 45 for t in temps_today).

When is a plain loop better than a comprehension?

Use a comprehension when Use a loop when
you build a new collection you only do side effects (print, write, append to another list)
it fits in one or two lines it needs more than two for or if clauses
each item needs one simple expression each item needs several steps or a try

[print(t) for t in temps] works, but it builds a list of None values that nobody uses. Write a loop for side effects.

Unpacking assigns the items of a sequence to several names in one statement (module 04). It removes index arithmetic such as pair[0] and pair[1].

low, high = 19.0, 23.0 # two names at once
low, high = high, low # swap without a temporary variable
print(low, high)
lowest, *middle, highest = sorted(temps) # star collects the rest
print(lowest, len(middle), highest)
limits = {"S1": (19.0, 23.0), "S2": (20.0, 26.0)}
for sensor_id, (low, high) in limits.items(): # nested unpacking
print(f"{sensor_id}: {low}-{high} C")
timestamp, sensor_id, _, _, vibration, status = (
"2024-05-01T08:00:00,S4,24.88,56.0,12.92,fail".split(",")
)
print(sensor_id, vibration, status)
Output
23.0 19.0
19.4 4 38.03
S1: 19.0-23.0 C
S2: 20.0-26.0 C
S4 12.92 fail

The name _ is a convention for “a value I do not need”. Unpacking also checks the length for you: if the line has 5 fields instead of 6, Python raises ValueError: not enough values to unpack (expected 6, got 5). An index-based version would fail later, or not at all.

Four idioms cover most text and file code:

Instead of Write Why
"Mean: " + str(round(m, 2)) + " C" f"Mean: {m:.2f} C" one readable template (module 02)
s = "" then s += part in a loop ", ".join(parts) one step; no slow repeated copies
os.path.join("data", "reports") Path("data") / "reports" a path object with methods (module 07)
f = open(...) … f.close() with path.open() as f: the file closes even after an error (module 11)
from pathlib import Path
reports = Path("data") / "reports"
names = [path.stem for path in sorted(reports.glob("*.csv"))]
print(", ".join(names))
total = 14162.33
print(f"{total=}") # the = shows the expression and its value
print(f"Revenue: {total:,.2f} USD")
Output
2024-01, 2024-02, 2024-03, 2024-04, 2024-05, 2024-06
total=14162.33
Revenue: 14,162.33 USD

path.stem is the file name without its suffix. sorted() puts the paths in a fixed order, because glob() returns them in the order the file system gives. The = in f"{total=}" is a debugging shortcut: it prints the expression, an equals sign and the value.

Data from files, forms and APIs is messy. A price can be "$79.99", "N/A" or empty. A JSON record can lack a key. You can handle this in two styles:

  • LBYL (“look before you leap”): check that an operation can succeed, then do it. if "phone" in record: phone = record["phone"].
  • EAFP (“easier to ask forgiveness than permission”): do the operation, and handle the exception if it fails. try: phone = record["phone"] except KeyError: phone = None.

Module 06 introduced both names. Python code often prefers EAFP, for three reasons:

  1. The check and the operation cannot drift apart. An LBYL check is a second, separate description of “valid input”. It can accept input that the operation rejects. Example 2 shows a real case: "²".isdigit() is True, but float("²") raises a ValueError.
  2. No race condition. A race condition is a bug that appears when the state of the world changes between two steps. if path.exists(): text = path.read_text() can still fail, because another program can delete the file between the check and the read. With EAFP, there is only one step.
  3. The normal case stays short. The happy path comes first. The error handling sits in one except clause.
record = {"customer_id": "C00002", "name": "James Okafor"} # no "phone" key
# LBYL: check, then act
if "phone" in record:
phone = record["phone"]
else:
phone = None
print("LBYL:", phone)
# EAFP: act, then handle the failure
try:
phone = record["phone"]
except KeyError:
phone = None
print("EAFP:", phone)
# For a dict lookup with a default, the idiom is neither: use get()
print("get():", record.get("phone"))
Output
LBYL: None
EAFP: None
get(): None

LBYL is the better choice in four cases:

Use LBYL when Example
the failure is common and the check is cheap and exact if not line.strip(): continue for blank lines
the operation has side effects you cannot undo validate every row before you write the output file
the exception would be too broad and could hide a bug check if denominator == 0 instead of a try around a long formula
the check is the business rule if quantity > MAX_QUANTITY: flag(row)

Two rules make EAFP safe:

  • Catch the specific exception, such as ValueError or KeyError. A bare except: also catches typos (NameError) and Ctrl+C (KeyboardInterrupt).
  • Keep the try block small: only the line that can fail. Put the code that uses the result in else or after the try statement.

PEP 8 is the official style guide for Python code (module 01). Tools enforce most of it for you (next section), but you should know the rules that tools cannot fix, mainly names.

Kind Style Examples
variable, function, method, module snake_case monthly_charges, read_rows(), clean_sales.py
class PascalCase (each word capitalized, no underscores) SensorReading, StandardScaler
constant UPPER_SNAKE_CASE MAX_QUANTITY = 50, DATA_DIR
internal (not part of the public interface) leading underscore _parse_line()
a name that clashes with a keyword trailing underscore class_, type_

A constant is a module-level name whose value the program never changes, such as a threshold or a file path. Python does not enforce it. The capital letters tell readers “do not reassign this”. A magic number is a bare number in code, such as if q > 50:. A named constant MAX_QUANTITY = 50 says what the number means and keeps it in one place.

Layout and other rules:

  • Indent with 4 spaces, never tabs.
  • PEP 8 limits lines to 79 characters. Many projects use 88, the default of the Black and ruff formatters. This course uses 88.
  • Two blank lines around top-level functions and classes. One blank line between methods.
  • Imports go at the top of the file, one module per line, in three groups: standard library, third-party packages, your own modules. Never from module import *.
  • Compare with None by identity: x is None, not x == None.
  • Do not compare booleans with ==: write if flagged:, not if flagged == True:.
  • Test for an empty sequence by its truthiness: if not rows:, not if len(rows) == 0:.
  • Write if key not in d:, not if not key in d:.
  • Check a type with isinstance(x, float), not type(x) == float, because isinstance also accepts subclasses.

PEP 8 itself warns that “a foolish consistency is the hobgoblin of little minds”. Follow the style of the project you work in. When a rule makes one line harder to read, break the rule for that line.

A linter reads code without running it and reports likely bugs and style problems. A formatter rewrites the layout of code into one consistent style. Ruff does both, and it is very fast. You set it up in the editor page. This section explains what it reports.

Each problem that ruff reports has a rule code: a prefix of letters for the rule family, then a number. F401 is “imported but unused”. B006 is “mutable default argument”. The families come from older tools that ruff reimplements:

Prefix Family (original tool) Finds Example
E, W pycodestyle PEP 8 layout and comparison problems E711 comparison to None with ==
F Pyflakes real errors: unused imports, undefined names F821 undefined name
I isort import order and grouping I001 unsorted imports
B flake8-bugbear likely bugs B006 mutable default, B023 late-binding loop variable
UP pyupgrade old syntax with a modern form UP006 List[int] instead of list[int]
SIM flake8-simplify code that can be simpler SIM115 open() without with
PTH flake8-use-pathlib os.path calls with a pathlib form PTH118 os.path.join()

By default, ruff checks only the E4, E7, E9 and F rules. You choose more families with select in pyproject.toml. This is the core of the configuration for the module 13 scripts. (The course file also excludes the deliberately messy demo scripts from folder runs.)

pyproject.toml
[tool.ruff]
line-length = 88
target-version = "py312"
[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "UP", "SIM", "PTH"]

The everyday commands:

Command Does
ruff check . lint every Python file in the folder; list the problems
ruff check --fix . apply the safe fixes, then list what remains
ruff check --fix --unsafe-fixes . also apply fixes that can change behavior; review them
ruff check --diff file.py show the fixes as a diff, change nothing
ruff format . reformat every file
ruff format --check . / --diff report or show what would change, change nothing
ruff rule B006 print the documentation of one rule

A safe fix keeps the behavior of the code, for example removing an unused import. An unsafe fix can change what the code does, for example replacing x == None with x is None (an object can define == in an unusual way). Ruff applies unsafe fixes only when you ask.

To silence one rule on one line, add a noqa comment: import pandas as pd # noqa: F401. “noqa” means “no quality assurance”. Always name the rule code, and use it rarely. A # ruff: noqa comment on its own line silences the whole file. Example 3 runs ruff on a real messy script.

A gotcha is a language behavior that surprises most people the first time and causes bugs. Python has a few famous ones. The next five sections show each one with real wrong output, then the fix.

Python evaluates a default value once, when it runs the def statement. It does not evaluate it again at each call. For an immutable default such as 0 or None, this makes no difference. For a mutable default such as [] or {}, every call that uses the default shares the same list.

def flag_reading(sensor_id, value, flagged=[]):
if value > 30:
flagged.append((sensor_id, value))
return flagged
print(flag_reading("S2", 38.03))
print(flag_reading("S3", 33.51)) # a new call, expected only S3
Output
[('S2', 38.03)]
[('S2', 38.03), ('S3', 33.51)]

The second call returns both readings. The list from the first call is still the default. In a pipeline that processes one file per call, results from earlier files leak into later ones.

The fix is the None sentinel: use None as the default and create the list inside the function. A sentinel is a special value that marks “no value given” (module 03).

def flag_reading(
sensor_id: str, value: float, flagged: list[tuple[str, float]] | None = None
) -> list[tuple[str, float]]:
if flagged is None:
flagged = [] # a new list on every call
if value > 30:
flagged.append((sensor_id, value))
return flagged
print(flag_reading("S2", 38.03))
print(flag_reading("S3", 33.51))
Output
[('S2', 38.03)]
[('S3', 33.51)]

Ruff reports the bug as B006 Do not use mutable data structures for argument defaults. Dataclasses have the same issue and solve it with field(default_factory=list) (module 21).

A closure is a function that remembers names from the scope where it was defined (module 05). It remembers the variable, not its value at that moment. Python looks the value up when the function runs. This is called late binding. A loop that creates functions makes all of them share the loop variable, which holds its last value when the loop ends.

The task: build one alert check per sensor, each with its own temperature limit.

limits = {"S1": 23.0, "S2": 25.0, "S3": 24.0, "S4": 27.0}
checks = {}
for sensor_id, limit in limits.items():
checks[sensor_id] = lambda temp: temp > limit
print(checks["S1"](24.5)) # 24.5 is above the S1 limit of 23.0
print(checks["S2"](26.0)) # 26.0 is above the S2 limit of 25.0
Output
False
False

Both checks answer False. When they run, the loop is over, and limit is 27.0, the limit of S4. Every check compares with 27.0.

The fix is early binding: capture the value when the function is created. The standard trick is a default argument, because defaults are evaluated at definition time (the same rule that causes gotcha 1):

checks = {}
for sensor_id, limit in limits.items():
checks[sensor_id] = lambda temp, limit=limit: temp > limit
print(checks["S1"](24.5), checks["S2"](26.0), checks["S4"](26.0))
Output
True True False

Two other fixes avoid the default-argument trick, which a caller could override by mistake. functools.partial() freezes argument values (module 09). A function factory, a function that builds and returns a function (module 05), gives each closure its own scope:

from collections.abc import Callable
def make_check(limit: float) -> Callable[[float], bool]:
def check(temp: float) -> bool:
return temp > limit
return check
checks = {sensor_id: make_check(limit) for sensor_id, limit in limits.items()}
print(checks["S1"](24.5), checks["S2"](26.0), checks["S4"](26.0))
Output
True True False

Each call of make_check() has its own limit, so each closure remembers a different value. Ruff reports the original bug as B023 Function definition does not bind loop variable.

== asks “do these two objects have equal values?”. is asks “are these two names the same object in memory?”. This second idea is identity. Two lists can be equal but not identical:

a = [21.0, 22.4]
b = [21.0, 22.4]
c = a # c is another name for the same list
print(a == b, a is b, a is c)
Output
True False True

The trap: for small integers and short strings, is often seems to work, because CPython (the standard Python interpreter from python.org) reuses some objects. CPython keeps one copy of each integer from -5 to 256 (the small integer cache), and it interns many strings that appear in the source code: it stores one shared copy. These are implementation details, not language rules. Values that you compute or read from a file are usually new objects:

import csv
FAIL = "fail"
with Path("data/sensors.csv").open(newline="", encoding="utf-8") as f:
statuses = [row["status"] for row in csv.DictReader(f)]
first_fail = next(s for s in statuses if s == FAIL)
print(first_fail == FAIL, first_fail is FAIL)
count_a = int("256")
count_b = int("256")
total_a = int("20228")
total_b = int("20228")
print(count_a is count_b, total_a is total_b)
Output
True False
True False

The status read from the file is equal to "fail", but it is a different object. 256 is cached, so is happens to say True; 20228 is not, so is says False. Code that uses is for values works in a quick test and fails on real data.

The rule is simple:

  • Use is only for singletons. A singleton is a value that has exactly one object: None, True, False. Write x is None.
  • Use == for every value comparison: numbers, strings, lists, dates.

Python warns you when you use is with a literal: status is "fail" gives SyntaxWarning: "is" with 'str' literal. Did you mean "=="?. Ruff reports it as F632.

A related trap in data work is NaN (“not a number”), the float value that pandas and NumPy use for a missing number. NaN is not equal to anything, not even to itself:

import math
missing = float("nan")
print(missing == missing, missing is missing, math.isnan(missing))
Output
False True True

So value == float("nan") is always False. Test with math.isnan(value), or in pandas with .isna() (module 26).

Module 01 showed that 0.1 + 0.2 is 0.30000000000000004. Floats store binary fractions, so most decimal fractions are approximate. Three consequences matter in data work.

Comparisons. Never compare two computed floats with ==. math.isclose(a, b) accepts a small relative difference (rel_tol, by default 1e-09). Near zero, a relative difference is meaningless, so add an absolute tolerance with abs_tol.

revenue = 3 * 249.00 * (1 - 0.1) # one line of data/sales.csv
print(revenue, revenue == 672.3, math.isclose(revenue, 672.3))
drift = 0.1 + 0.2 - 0.3
print(drift, math.isclose(drift, 0.0), math.isclose(drift, 0.0, abs_tol=1e-9))
Output
672.3000000000001 False True
5.551115123125783e-17 False True

Accumulation. A long chain of additions collects tiny errors. A manual total += x loop adds them up. Since Python 3.12, the built-in sum() uses a compensated algorithm for floats that cancels most of the error. math.fsum() is exact to the last bit.

total = 0.0
for _ in range(10):
total += 0.1 # ten payments of 0.1
print(total, sum([0.1] * 10), math.fsum([0.1] * 10))
Output
0.9999999999999999 1.0 1.0

Rounding money. round() works on the binary value. 129.95 * 0.9 is stored as slightly less than 116.955, so round() gives 116.95, while an invoice rule “round half up” expects 116.96. The decimal module does exact decimal arithmetic. A Decimal built from a string stores exactly the digits you write. quantize() rounds it to a fixed number of decimals with the rule you choose.

from decimal import ROUND_HALF_UP, Decimal
print(129.95 * 0.9, round(129.95 * 0.9, 2))
price = Decimal("129.95")
line_total = price * (1 - Decimal("0.1"))
print(line_total, line_total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
print(Decimal(0.1)) # built from a float: the binary error comes along
Output
116.955 116.95
116.955 116.96
0.1000000000000000055511151231257827021181583404541015625

Build a Decimal from a string, never from a float: Decimal(0.1) shows the full binary value that the float really holds. Use Decimal for invoices, payments and anything that must match an accounting system to the cent. Use floats for analysis, statistics and machine learning, where NumPy and pandas need them and tiny errors do not change conclusions.

Gotcha 5: changing a list while you iterate over it

Section titled “Gotcha 5: changing a list while you iterate over it”

A for loop over a list keeps an internal position: item 0, then item 1, then item 2. If the loop body removes an item, the items after it shift one place to the left, and the loop skips the item that moved into the current position.

Sensor gateways often write -999.0 as a code for “no reading”. The task: remove those codes.

readings = [21.0, -999.0, -999.0, 22.4, -999.0, 21.9]
for value in readings:
if value == -999.0:
readings.remove(value)
print(readings)
Output
[21.0, 22.4, -999.0, 21.9]

One -999.0 survives. The loop removed the code at position 1. The second code moved into position 1, and the loop went on to position 2, so it never saw it. No error, just a wrong result.

Build a new list instead. A comprehension says exactly what to keep:

readings = [21.0, -999.0, -999.0, 22.4, -999.0, 21.9]
readings = [value for value in readings if value != -999.0]
print(readings)
Output
[21.0, 22.4, 21.9]

If other code holds a reference to the same list and must see the change, assign to the full slice: readings[:] = [...] replaces the contents of the existing list. You can also loop over a copy, for value in list(readings):, and remove from the original, but that is slower and harder to read.

A dict protects itself. Adding or deleting keys while you loop over it raises an error:

last_seen = {"S1": "2024-05-14", "S2": None, "S3": "2024-05-14", "S4": None}
for sensor_id, day in last_seen.items():
if day is None:
del last_seen[sensor_id]
Output
RuntimeError: dictionary changed size during iteration

The fix is the same idea: build a new dict, {k: v for k, v in last_seen.items() if v is not None}, or loop over a copy of the keys, for sensor_id in list(last_seen):.

To refactor is to change the structure of code without changing what it does (module 01). Messy data scripts are worth refactoring, because you rerun and change them for months. The risk is that a “harmless” cleanup changes a number in the report. A characterization test protects you: before you change anything, you run the old code and record its output. After each change, you compare the new output with the recording. The name says that the test describes (characterizes) what the code does now, right or wrong.

flowchart LR
    A["Run the old script"] --> B["Record its output"]
    B --> C["Change one thing"]
    C --> D{"Same output?"}
    D -- yes --> E["Next change"]
    E --> C
    D -- no --> F["Undo or explain"]
    F --> C

Three rules keep a refactor safe:

  1. One change at a time. Replace the file handling, compare, then replace the counting loop, compare.
  2. Refactor and fix in separate steps. If you find a bug, finish the refactor with the bug in place, then fix it as a visible change that alters the recorded output.
  3. Keep the check after the refactor. The comparison becomes a regression test. Module 14 turns it into a pytest test.

Example 1 — Summarize one day of sensor readings

Section titled “Example 1 — Summarize one day of sensor readings”

Goal: A facility team wants a daily quality summary of data/sensors.csv for 2024-05-01: blank cells with their line numbers, status counts, the mean temperature per sensor and two quality flags. Write it with idioms only: no index loops and no manual counters.

import csv
from pathlib import Path
with Path("data/sensors.csv").open(newline="", encoding="utf-8") as f:
day = [
row for row in csv.DictReader(f) if row["timestamp"].startswith("2024-05-01")
]
print(len(day))
print(day[0]["sensor_id"], day[0]["temperature_c"], day[0]["status"])
Output
576
S1 20.21 ok

with closes the file when the block ends. The comprehension keeps only the rows of May 1: 4 sensors × 144 ten-minute readings. csv.DictReader gives each row as a dict, so the code says row["status"] instead of row[5].

Step 2 — Find blank cells with their line numbers

Section titled “Step 2 — Find blank cells with their line numbers”
NUMERIC_COLUMNS = ("temperature_c", "humidity_pct", "vibration_mm_s")
blanks = [
(line_number, column)
for line_number, row in enumerate(day, start=2) # line 1 is the header
for column in NUMERIC_COLUMNS
if not row[column]
]
print(blanks)
Output
[(103, 'temperature_c'), (329, 'vibration_mm_s'), (384, 'humidity_pct'), (486, 'humidity_pct')]

enumerate(day, start=2) numbers the rows as an editor shows the file lines, because the header is line 1 and May 1 is at the top of the file. An empty string is falsy, so not row[column] finds a blank cell. This comprehension has two for clauses and one if. That is the most a comprehension should have.

from collections import Counter
status_counts: dict[str, int] = {}
for row in day:
status_counts[row["status"]] = status_counts.get(row["status"], 0) + 1
print(status_counts)
print(Counter(row["status"] for row in day))
Output
{'ok': 570, 'warn': 5, 'fail': 1}
Counter({'ok': 570, 'warn': 5, 'fail': 1})

Both lines count the same thing. get(status, 0) returns 0 for a status that the dict has not seen yet. Counter does the whole job in one call and prints the most common values first. Choose Counter when counting is the point of the code.

Step 4 — Group the temperatures by sensor

Section titled “Step 4 — Group the temperatures by sensor”
temps_by_sensor: dict[str, list[float]] = {}
for row in day:
if row["temperature_c"]: # skip the one blank cell (LBYL: common and cheap)
temp = float(row["temperature_c"])
temps_by_sensor.setdefault(row["sensor_id"], []).append(temp)
for sensor_id, temps in sorted(temps_by_sensor.items()):
mean = sum(temps) / len(temps)
print(f"{sensor_id}: {len(temps)} readings, mean {mean:.2f} C, max {max(temps)} C")
Output
S1: 144 readings, mean 22.06 C, max 24.96 C
S2: 143 readings, mean 24.49 C, max 38.03 C
S3: 144 readings, mean 21.29 C, max 33.51 C
S4: 144 readings, mean 26.04 C, max 28.41 C

setdefault() creates the list for a sensor the first time and appends to it after that. sorted(... .items()) gives the sensors in a fixed order, and the loop unpacks each (key, value) pair. S2 has 143 readings because of the blank cell at line 103.

any_fail = any(row["status"] == "fail" for row in day)
all_sensors = all(s in temps_by_sensor for s in ("S1", "S2", "S3", "S4"))
first_fail = next((row for row in day if row["status"] == "fail"), None)
print(f"Any fail: {any_fail}. All sensors reported: {all_sensors}.")
if first_fail is not None:
print(f"First fail: {first_fail['sensor_id']} at {first_fail['timestamp']}")
Output
Any fail: True. All sensors reported: True.
First fail: S4 at 2024-05-01T08:00:00

any() stops at the first fail row. next(generator, None) is the idiom for “the first match, or None if there is none”. Without the default None, next() raises StopIteration when nothing matches. The first failure is S4 at 08:00, with a vibration of 12.92 mm/s, above the fail limit of 11.2 mm/s.

Common mistakes:

  • Writing for i in range(len(day)): and day[i]["status"]. It works, but every [i] is a chance for an off-by-one error.
  • Forgetting start=2 in enumerate(). The reported line numbers are then off by two, and nobody can find the blank cells in the file.
  • Using next(row for row in day if ...) without a default. On a day with no failure, the script crashes with StopIteration.
  • Using all() as a quality gate without checking that there is data. all() of an empty iterable is True.

Example 2 — Parse messy records: LBYL or EAFP

Section titled “Example 2 — Parse messy records: LBYL or EAFP”

Goal: Two real inputs have gaps. data/customers.json has optional fields, and the unit_price column of data/sales_raw.csv mixes "$79.99", "$1,299.00", "N/A", "-" and empty cells. Parse both, compare the LBYL and EAFP styles, and find where they really differ.

import json
export = json.loads(Path("data/customers.json").read_text(encoding="utf-8"))
customers = export["customers"]
with_phone_key = sum("phone" in c for c in customers)
phone_null = [c["customer_id"] for c in customers if c.get("phone", "") is None]
no_postal = [c["customer_id"] for c in customers if "postal_code" not in c["address"]]
print(len(customers), with_phone_key, phone_null, no_postal)
Output
20 7 ['C00010'] ['C00005', 'C00014']

7 of the 20 records have a phone key, and one of those holds null (Python None). Two addresses have no postal_code. A parser must handle three cases for the phone: a value, None and no key at all.

Step 2 — Write the contact line in LBYL style

Section titled “Step 2 — Write the contact line in LBYL style”
from typing import Any
def contact_lbyl(c: dict[str, Any]) -> str:
if "phone" in c and c["phone"] is not None:
phone = c["phone"]
else:
phone = "no phone"
if "postal_code" in c["address"]:
postal_code = c["address"]["postal_code"]
else:
postal_code = "?"
return f"{c['customer_id']} {c['address']['city']} {postal_code} {phone}"
for c in customers[3:6]:
print(contact_lbyl(c))
Output
C00004 Philadelphia 78449 +1-555-652-5039
C00005 Chicago ? no phone
C00006 Chicago 48100 no phone

Every optional field needs its own if/else. The code is correct but long, and the real work, building the line, is hidden at the bottom.

Step 3 — Use dict.get for optional fields

Section titled “Step 3 — Use dict.get for optional fields”
def contact(c: dict[str, Any]) -> str:
phone = c.get("phone") or "no phone" # handles a missing key and None
postal_code = c["address"].get("postal_code", "?")
return f"{c['customer_id']} {c['address']['city']} {postal_code} {phone}"
for c in customers[3:6]:
print(contact(c))
assert all(contact(c) == contact_lbyl(c) for c in customers)
Output
C00004 Philadelphia 78449 +1-555-652-5039
C00005 Chicago ? no phone
C00006 Chicago 48100 no phone

For an optional dict key, get() is the idiom. It is neither LBYL nor EAFP: the dict answers “the value or a default” in one call. c.get("phone") returns None both for a missing key and for a null value, and or "no phone" replaces it. The assert proves that both versions agree on all 20 records. Note that or also replaces other falsy values, such as an empty string; here that is what we want.

with Path("data/sales_raw.csv").open(newline="", encoding="utf-8") as f:
raw_prices = [row["unit_price"] for row in csv.DictReader(f)]
print(raw_prices[:3])
print(sorted({p for p in raw_prices if not p.startswith("$")}))
print(next(p for p in raw_prices if "," in p))
Output
['$249.00', '$29.99', '$89.50']
['', '-', 'N/A']
$1,299.00

The prices are text with a dollar sign. The set comprehension collects the distinct values that do not start with $: the three missing-value tokens. Some prices have a thousands separator.

Step 5 — Write the parser in both styles

Section titled “Step 5 — Write the parser in both styles”
def parse_price_lbyl(text: str) -> float | None:
cleaned = text.removeprefix("$").replace(",", "")
if cleaned.replace(".", "", 1).isdigit(): # check first
return float(cleaned)
return None
def parse_price(text: str) -> float | None:
try:
return float(text.removeprefix("$").replace(",", "")) # just try it
except ValueError:
return None
lbyl = [parse_price_lbyl(p) for p in raw_prices]
eafp = [parse_price(p) for p in raw_prices]
print(sum(p is not None for p in eafp), sum(p is None for p in eafp), lbyl == eafp)
Output
1190 10 True

On this file, both parsers agree: 1,190 prices and 10 missing values. The LBYL version tests “digits with at most one decimal point”. The EAFP version lets float() decide and catches only ValueError, so a typo in the function still raises its own error.

Step 6 — Find the inputs where the styles differ

Section titled “Step 6 — Find the inputs where the styles differ”
for text in ["$ 12.50", "-5.00", "1e3", "nan", "²"]:
try:
checked = parse_price_lbyl(text)
except ValueError as err:
checked = f"crash: {err}"
print(f"{text!r:10} EAFP: {parse_price(text)!r:8} LBYL: {checked!r}")
Output
'$ 12.50' EAFP: 12.5 LBYL: None
'-5.00' EAFP: -5.0 LBYL: None
'1e3' EAFP: 1000.0 LBYL: None
'nan' EAFP: nan LBYL: None
'²' EAFP: None LBYL: "crash: could not convert string to float: '²'"

The two styles describe “valid” in two different ways, and the descriptions drift apart:

  • "²" (superscript two) passes the isdigit() check, but float() rejects it. The LBYL parser crashes on input it approved.
  • float() accepts spaces, a minus sign, scientific notation and "nan". The EAFP parser accepts -5.0 and nan as prices.

The lesson is not “EAFP always wins”. Use EAFP for the question “can this text be read as a number?”, because only float() knows the full answer. Then use an explicit LBYL check for your business rule, such as price is not None and math.isfinite(price) and price > 0.

Common mistakes:

  • Writing except: or except Exception: around the parse. It hides real bugs, such as a NameError from a typo.
  • Putting the whole loop inside one try. The first bad price then stops the loop. Keep the try around the one line that can fail.
  • Trusting str.isdigit() as a number check. It accepts characters that float() rejects and rejects text that float() accepts.
  • Treating a parsed value as valid. float() returns nan, inf and negative values without complaint.

Example 3 — Lint and format a messy script with ruff

Section titled “Example 3 — Lint and format a messy script with ruff”

Goal: A colleague’s script summarizes data/readings.txt. It works, but it is hard to maintain. Run ruff on it, apply the automatic fixes, preview the formatter and finish the clean-up by hand.

messy.py
import os, sys
import json
from typing import List, Dict
def read_values(path, skipped = []):
f = open(path)
values = []
for line in f.readlines():
try:
values.append(float(line))
except:
skipped.append(line)
f.close()
return values, skipped
def summarize(values: List[float]) -> Dict[str, float]:
if len(values) == 0: return {}
total = 0
for i in range(len(values)):
total = total + values[i]
return {'count': len(values), 'mean': total/len(values), 'max': max(values)}
values, skipped = read_values(os.path.join('data', 'readings.txt'))
stats = summarize(values)
print("Valid readings: {}".format(stats['count']))
print("Mean: %.2f C" % stats['mean'])
print("Skipped lines: " + str(len(skipped)))
alert = stats['max'] > 22.5
if alert == True:
print("Warning: max above 22.5 C")
Output
Valid readings: 40
Mean: 21.06 C
Skipped lines: 3
Warning: max above 22.5 C

The output is correct: 40 valid readings, 3 broken lines. The problems are in the code, not the result.

Terminal
ruff check --output-format concise messy.py
Output
messy.py:1:1: E401 [*] Multiple imports on one line
messy.py:1:1: I001 [*] Import block is un-sorted or un-formatted
messy.py:1:12: F401 [*] `sys` imported but unused
messy.py:2:8: F401 [*] `json` imported but unused
messy.py:3:1: UP035 `typing.List` is deprecated, use `list` instead
messy.py:3:1: UP035 `typing.Dict` is deprecated, use `dict` instead
messy.py:5:33: B006 Do not use mutable data structures for argument defaults
messy.py:6:9: PTH123 `open()` should be replaced by `Path.open()`
messy.py:6:9: SIM115 Use a context manager for opening files
messy.py:11:9: E722 Do not use bare `except`
messy.py:16:23: UP006 [*] Use `list` instead of `List` for type annotation
messy.py:16:39: UP006 [*] Use `dict` instead of `Dict` for type annotation
messy.py:17:24: E701 Multiple statements on one line (colon)
messy.py:23:31: PTH118 `os.path.join()` should be replaced by `Path` with `/` operator
messy.py:26:7: UP031 Use format specifiers instead of percent format
messy.py:29:4: E712 Avoid equality comparisons to `True`; use `alert:` for truth checks
Found 16 errors.
[*] 6 fixable with `--fix` (3 unsafe fixes available with `--fix --unsafe-fixes`).

Each line gives the file, the line and column, the rule code and a message. [*] marks a problem with a safe automatic fix. The --output-format concise option prints one line per problem. Without it, ruff also shows the code around each problem and the proposed fix.

The findings, grouped by kind:

  • Real bugs: B006 (the skipped=[] default is shared between calls, gotcha 1) and E722 (the bare except would also hide a typo).
  • Resource handling: SIM115 and PTH123 (open() without with).
  • Dead or outdated code: F401 (unused imports), UP035 and UP006 (typing.List instead of list), UP031 (% formatting).
  • Style: E401, I001, E701, E712, PTH118.
Terminal
ruff check --fix --output-format concise messy.py
Output
messy.py:4:33: B006 Do not use mutable data structures for argument defaults
messy.py:5:9: PTH123 `open()` should be replaced by `Path.open()`
messy.py:5:9: SIM115 Use a context manager for opening files
messy.py:10:9: E722 Do not use bare `except`
messy.py:16:24: E701 Multiple statements on one line (colon)
messy.py:22:31: PTH118 `os.path.join()` should be replaced by `Path` with `/` operator
messy.py:25:7: UP031 Use format specifiers instead of percent format
messy.py:28:4: E712 Avoid equality comparisons to `True`; use `alert:` for truth checks
Found 16 errors (8 fixed, 8 remaining).
3 unsafe fixes available with `--fix --unsafe-fixes`.

Ruff fixed 8 problems in place: it removed the unused imports, split and sorted the imports and replaced List and Dict with list and dict. The first run said only 6 were fixable. The other 2 are the UP035 findings: once UP006 replaced List and Dict, the typing import was unused, and --fix removed it. Eight problems remain. Three of them have unsafe fixes, which ruff applies only with --unsafe-fixes. The others need a decision from a person: what should except catch, and where does the file open?

Terminal
ruff format --diff messy.py
Output
--- messy.py
+++ messy.py
@@ -1,7 +1,7 @@
import os
-def read_values(path, skipped = []):
+def read_values(path, skipped=[]):
f = open(path)
values = []
for line in f.readlines():
@@ -12,18 +12,21 @@
f.close()
return values, skipped
+
def summarize(values: list[float]) -> dict[str, float]:
- if len(values) == 0: return {}
+ if len(values) == 0:
+ return {}
total = 0
for i in range(len(values)):
total = total + values[i]
- return {'count': len(values), 'mean': total/len(values), 'max': max(values)}
+ return {"count": len(values), "mean": total / len(values), "max": max(values)}
-values, skipped = read_values(os.path.join('data', 'readings.txt'))
+
+values, skipped = read_values(os.path.join("data", "readings.txt"))
stats = summarize(values)
-print("Valid readings: {}".format(stats['count']))
-print("Mean: %.2f C" % stats['mean'])
+print("Valid readings: {}".format(stats["count"]))
+print("Mean: %.2f C" % stats["mean"])
print("Skipped lines: " + str(len(skipped)))
-alert = stats['max'] > 22.5
+alert = stats["max"] > 22.5
if alert == True:
print("Warning: max above 22.5 C")
1 file would be reformatted

This output is a diff: a list of line changes between two versions of a file. Lines that start with - go, lines that start with + come in, and lines that start with a space stay. A line such as @@ -12,18 +12,21 @@ says where the next change is. The formatter changes only the layout. It removes the spaces around = in a default value, adds a second blank line before summarize() and before the main code, splits if ...: return {} into two lines, adds spaces around / and turns single quotes into double quotes. --diff changes nothing; ruff format messy.py would write the changes.

readings_report.py
"""Summarize the temperature readings in data/readings.txt."""
from pathlib import Path
READINGS_PATH = Path("data") / "readings.txt"
ALERT_C = 22.5 # facility rule: warn above 22.5 °C
def read_values(path: Path) -> tuple[list[float], list[str]]:
"""Return the valid readings and the raw lines that are not numbers."""
values: list[float] = []
skipped: list[str] = []
with path.open(encoding="utf-8") as f:
for line in f:
try:
values.append(float(line))
except ValueError:
skipped.append(line)
return values, skipped
def summarize(values: list[float]) -> dict[str, float]:
"""Return the count, mean and maximum of the readings."""
if not values:
return {}
return {"count": len(values), "mean": sum(values) / len(values), "max": max(values)}
def main() -> None:
"""Print the summary of data/readings.txt."""
values, skipped = read_values(READINGS_PATH)
stats = summarize(values)
print(f"Valid readings: {stats['count']}")
print(f"Mean: {stats['mean']:.2f} C")
print(f"Skipped lines: {len(skipped)}")
if stats["max"] > ALERT_C:
print(f"Warning: max above {ALERT_C} C")
if __name__ == "__main__":
main()
Output
Valid readings: 40
Mean: 21.06 C
Skipped lines: 3
Warning: max above 22.5 C

The output is identical. The manual changes, with the rule each one answers:

  1. B006: read_values() creates skipped inside the function, so each call starts empty.
  2. SIM115, PTH123, PTH118: with path.open(...) and Path("data") / "readings.txt". The file closes even if a line fails.
  3. E722: except ValueError catches only “not a number”.
  4. E701, E712, UP031: if not values: on its own line, if stats["max"] > ALERT_C: and f-strings.
  5. No rule asked for these: sum(values) replaces the index loop, the constant ALERT_C replaces the magic number 22.5, and main() with if __name__ == "__main__": lets other code import the functions without running the report (module 08).
Terminal
ruff check readings_report.py && ruff format --check readings_report.py
Output
All checks passed!
1 file already formatted

&& runs the second command only if the first one succeeds. Both pass. In a team, the same two commands run in continuous integration (CI), a service that runs the project’s checks on every proposed change. Messy code then cannot come back.

Common mistakes:

  • Running ruff check --fix --unsafe-fixes without reading the diff. An unsafe fix can change behavior. Run ruff check --diff --unsafe-fixes first.
  • Silencing a finding with # noqa instead of fixing it. A B006 or E722 finding is a real bug.
  • Running only the formatter. ruff format fixes layout, not bugs. Run ruff check too.
  • Thinking a clean ruff report means clean code. Ruff did not ask for any of the changes in item 5.

Example 4 — Fix a batch parser with three gotchas

Section titled “Example 4 — Fix a batch parser with three gotchas”

Goal: A sensor gateway sends one text line per batch: sensor id, status and readings, separated by ;. The code -999.0 marks a missing reading. A parser must return the clean readings, a failure flag and the number of dropped codes. It gives wrong answers. Find and fix the three bugs.

MISSING = -999.0
FAIL = "fail"
def parse_batch(line, dropped=[]):
sensor_id, status, raw = line.split(";")
values = [float(x) for x in raw.split(",")]
for value in values:
if value == MISSING:
values.remove(value)
dropped.append(value)
return sensor_id, values, status is FAIL, len(dropped)
print(parse_batch("S4;fail;24.88,-999.0,-999.0,25.1"))
print(parse_batch("S1;ok;20.21,-999.0,20.4"))
Output
('S4', [24.88, -999.0, 25.1], False, 1)
('S1', [20.21, 20.4], False, 2)

The right answers are ('S4', [24.88, 25.1], True, 2) and ('S1', [20.21, 20.4], False, 1). Three bugs cause four wrong values: a -999.0 survives in S4, the S4 failure flag is False, the S4 drop count is 1 instead of 2, and the S1 drop count is 2 instead of 1.

Step 2 — Fix the loop that changes its own list

Section titled “Step 2 — Fix the loop that changes its own list”
values = [24.88, -999.0, -999.0, 25.1]
clean = [v for v in values if v != MISSING]
print(clean, len(values) - len(clean))
Output
[24.88, 25.1] 2

values.remove() inside for value in values skipped the second of two adjacent codes (gotcha 5). The comprehension builds a new list, and the difference in length gives the drop count. No accumulator is needed.

sensor_id, status, raw = "S4;fail;24.88,-999.0,-999.0,25.1".split(";")
print(status == FAIL, status is FAIL)
Output
True False

split() creates a new string object. It is equal to "fail", but it is not the same object as the constant FAIL (gotcha 3). Compare values with ==.

def parse_batch(line: str) -> tuple[str, list[float], bool, int]:
"""Return the sensor id, clean readings, failure flag and dropped count."""
sensor_id, status, raw = line.split(";")
values = [float(x) for x in raw.split(",")]
clean = [v for v in values if v != MISSING]
return sensor_id, clean, status == FAIL, len(values) - len(clean)
first = parse_batch("S4;fail;24.88,-999.0,-999.0,25.1")
second = parse_batch("S1;ok;20.21,-999.0,20.4")
print(first)
print(second)
assert first == ("S4", [24.88, 25.1], True, 2)
assert second == ("S1", [20.21, 20.4], False, 1)
Output
('S4', [24.88, 25.1], True, 2)
('S1', [20.21, 20.4], False, 1)

The dropped=[] default is gone, so nothing survives between calls (gotcha 1). Each call depends only on its argument. A function like this is a pure function (module 05): easy to test and safe to call in any order.

Common mistakes:

  • Fixing only the first wrong number you see. The first call hid two bugs, and the third bug appeared only on the second call. Test a function with at least two different calls.
  • Replacing dropped=[] with dropped=None and keeping the shared accumulator design. Return the count instead.
  • Expecting ruff to find all three. Ruff reports B006 here. Its rule for changing a list during a loop (B909) is still in preview, the opt-in group of new rules that you enable with --preview. No rule flags is between two variables.

Example 5 — Price an invoice exactly with Decimal

Section titled “Example 5 — Price an invoice exactly with Decimal”

Goal: A shop invoices each order line as unit price × quantity × (1 − discount), rounded half up to the cent, the rule its accounting system uses. Show where floats break this rule, price an invoice with Decimal, and reconcile the two-year revenue total of data/sales.csv.

unit_price, quantity, discount = 129.95, 1, 0.1 # Chef's Knife Set, 10% off
line_total = unit_price * quantity * (1 - discount)
print(line_total, round(line_total, 2))
print(f"{line_total:.20f}")
Output
116.955 116.95
116.95499999999999829470

The exact result is 116.955, so “round half up” gives 116.96. Python prints 116.955, the shortest text that maps back to the stored float. The stored value is slightly smaller, as the 20 decimals show, so round() gives 116.95. One cent is wrong.

Step 2 — Price the same line with Decimal

Section titled “Step 2 — Price the same line with Decimal”
from decimal import ROUND_HALF_UP, Decimal
CENT = Decimal("0.01")
def line_amount(unit_price: str, quantity: int, discount: str) -> Decimal:
gross = Decimal(unit_price) * quantity
return (gross * (1 - Decimal(discount))).quantize(CENT, rounding=ROUND_HALF_UP)
print(line_amount("129.95", 1, "0.1"))
Output
116.96

The prices arrive as text from a file or a database, so the function takes strings and builds each Decimal from them. Decimal arithmetic on 129.95 × 0.9 is exact: 116.955. quantize(CENT, rounding=ROUND_HALF_UP) rounds it to cents with the accounting rule. An int such as quantity mixes safely with a Decimal.

lines = [
("Chef's Knife Set", "129.95", 1, "0.1"),
("Running Socks 3-Pack", "14.99", 5, "0.1"),
("Merino Wool Sweater", "89.50", 3, "0.05"),
]
total = Decimal("0")
for product, price, qty, disc in lines:
amount = line_amount(price, qty, disc)
total += amount
print(f"{product:<22} {qty:>2} x {price:>7} {amount:>8}")
print(f"{'Total':<36} {total:>8}")
Output
Chef's Knife Set 1 x 129.95 116.96
Running Socks 3-Pack 5 x 14.99 67.46
Merino Wool Sweater 3 x 89.50 255.08
Total 439.50

All three lines end in a half cent, and all three round up. Format specs work on Decimal values, so the columns line up as with floats. The total is the sum of the rounded lines, as on a real invoice.

Step 4 — See why you must not mix Decimal and float

Section titled “Step 4 — See why you must not mix Decimal and float”
print(Decimal("129.95") * 0.9)
Output
TypeError: unsupported operand type(s) for *: 'decimal.Decimal' and 'float'

Python refuses to multiply a Decimal by a float, because the float would bring its binary error into the exact calculation. Convert the other value from text: Decimal("0.9"). Do not use Decimal(0.9) either; it copies the binary error.

with Path("data/sales.csv").open(newline="", encoding="utf-8") as f:
revenues = [row["revenue"] for row in csv.DictReader(f)]
running = 0.0
for text in revenues:
running += float(text) # a manual running total
print(len(revenues), repr(running))
print(repr(sum(float(t) for t in revenues)), sum(Decimal(t) for t in revenues))
print(math.isclose(running, 3596523.83))
Output
20228 3596523.8300009277
3596523.83 3596523.83
True

The manual loop over 20,228 lines collects an error of about 0.000001. sum() cancels it, and Decimal is exact. For reporting, the float total is fine: math.isclose() confirms it. For a ledger that must balance to the cent, sum Decimal values.

Common mistakes:

  • Building a Decimal from a float: Decimal(129.95) is 129.94999999999998863131622783839702606201171875.
  • Rounding with round() and expecting “half up”. Python’s round() rounds halves to even, and it works on the binary value.
  • Rounding the total instead of each line. An invoice shows rounded lines, and its total must equal their sum.
  • Using Decimal in a pandas or NumPy calculation. They are built on floats; Decimal columns become slow object columns.

Example 6 — Refactor a monthly report script

Section titled “Example 6 — Refactor a monthly report script”

Goal: A script summarizes the six monthly extracts in data/reports/: lines, revenue and top category per month, and the grand total. It works, but it uses os.path, manual file closing, index loops and hand-written counting. Refactor it into Pythonic code, and prove with a characterization check that the output stays the same.

Step 1 — Run the original and record its output

Section titled “Step 1 — Run the original and record its output”
import os
def report_before(folder):
names = os.listdir(folder)
names.sort()
result = []
grand = 0
for i in range(len(names)):
name = names[i]
if not name.endswith(".csv"):
continue
f = open(os.path.join(folder, name))
lines = f.readlines()
f.close()
header = lines[0].strip().split(",")
rev_col = header.index("revenue")
cat_col = header.index("category")
total = 0
cats = {}
for j in range(1, len(lines)):
parts = lines[j].strip().split(",")
total = total + float(parts[rev_col])
c = parts[cat_col]
if c in cats:
cats[c] = cats[c] + 1
else:
cats[c] = 1
top = None
for c in cats:
if top == None or cats[c] > cats[top]:
top = c
grand = grand + total
result.append(name[:-4] + ": " + str(len(lines) - 1) + " lines, revenue "
+ str(round(total, 2)) + ", top category " + top)
result.append("Total revenue: " + str(round(grand, 2)))
return result
expected = report_before("data/reports")
print("\n".join(expected))
Output
2024-01: 48 lines, revenue 14162.33, top category Electronics
2024-02: 48 lines, revenue 4719.04, top category Beauty
2024-03: 47 lines, revenue 12296.72, top category Electronics
2024-04: 52 lines, revenue 10879.04, top category Sports
2024-05: 47 lines, revenue 6675.86, top category Clothing
2024-06: 55 lines, revenue 8533.4, top category Sports
Total revenue: 57266.39

expected is the recorded output: the characterization. The function returns its lines instead of printing them, so the check can compare lists. header.index() finds the columns by name, which matters because 2024-04.csv has its columns in a different order.

report.py (diff)
names = os.listdir(folder)
names.sort()
for i in range(len(names)):
name = names[i]
if not name.endswith(".csv"):
continue
f = open(os.path.join(folder, name))
lines = f.readlines()
f.close()
header = lines[0].strip().split(",")
rev_col = header.index("revenue")
for path in sorted(folder.glob("*.csv")):
with path.open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
total = 0
for j in range(1, len(lines)):
parts = lines[j].strip().split(",")
total = total + float(parts[rev_col])
total = sum(float(row["revenue"]) for row in rows)

The red lines go and the green lines come in. The new lines move into a function summarize_month(path) in Step 4. folder.glob("*.csv") lists only the CSV files, so the endswith filter goes. csv.DictReader finds the columns by name from the header, so the index() calls go. It also parses quoted fields correctly, which split(",") does not: a product name with a comma would break the old script.

Step 3 — Replace the counting and the search for the maximum

Section titled “Step 3 — Replace the counting and the search for the maximum”
report.py (diff)
cat_col = header.index("category")
cats = {}
c = parts[cat_col] # inside the row loop
if c in cats:
cats[c] = cats[c] + 1
else:
cats[c] = 1
top = None
for c in cats:
if top == None or cats[c] > cats[top]:
top = c
top_category, _ = Counter(row["category"] for row in rows).most_common(1)[0]

Counter replaces eleven lines of counting and searching. most_common(1) returns a list with one (category, count) pair, and the unpacking keeps the category. There is one subtle point. In April, Sports and Home tie with 10 lines each. The old loop walks the dict in first-seen order and replaces the leader only on a strictly larger count (>), so it keeps the tied category that appears first in the file. most_common() also keeps the first-seen value among ties. The check in the next step confirms that the two agree.

Step 4 — Run the refactored version and compare

Section titled “Step 4 — Run the refactored version and compare”
from collections import Counter
def summarize_month(path: Path) -> tuple[int, float, str]:
"""Return the line count, revenue and top category of one monthly extract."""
with path.open(newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
total = sum(float(row["revenue"]) for row in rows)
top_category, _ = Counter(row["category"] for row in rows).most_common(1)[0]
return len(rows), total, top_category
def report_after(folder: Path) -> list[str]:
"""Return one line per month and a final total line."""
lines = []
grand_total = 0.0
for path in sorted(folder.glob("*.csv")):
count, total, top = summarize_month(path)
grand_total += total
revenue = round(total, 2)
lines.append(
f"{path.stem}: {count} lines, revenue {revenue}, top category {top}"
)
lines.append(f"Total revenue: {round(grand_total, 2)}")
return lines
after = report_after(Path("data/reports"))
print(after == expected)
assert after == expected
Output
True

The output is identical, line for line. The new code splits the work in two functions: one month, and the whole folder. Each has a name that says what it does, type hints and a docstring. summarize_month() can now be tested on its own (module 14).

Step 5 — See the check catch a behavior change

Section titled “Step 5 — See the check catch a behavior change”
def report_two_decimals(folder: Path) -> list[str]:
"""The same report, with every revenue shown with two decimals."""
lines = []
grand_total = 0.0
for path in sorted(folder.glob("*.csv")):
count, total, top = summarize_month(path)
grand_total += total
lines.append(
f"{path.stem}: {count} lines, revenue {total:.2f}, top category {top}"
)
lines.append(f"Total revenue: {grand_total:.2f}")
return lines
candidate = report_two_decimals(Path("data/reports"))
for old, new in zip(expected, candidate, strict=True):
if old != new:
print("before:", old)
print("after: ", new)
Output
before: 2024-06: 55 lines, revenue 8533.4, top category Sports
after: 2024-06: 55 lines, revenue 8533.40, top category Sports

:.2f looks like a harmless cleanup of round(total, 2), but it is a behavior change: June now shows 8533.40 instead of 8533.4. The check found the one line out of seven that changed. Maybe two decimals is better. Then make that change in a separate, visible step, and update the recorded output on purpose.

Common mistakes:

  • Refactoring without a recorded output. A cleanup like round() → :.2f then reaches a report without anybody noticing.
  • Changing several things at once and then finding a difference. You cannot tell which change caused it. Compare after each step.
  • Assuming sorted(os.listdir()) and sorted(folder.glob(...)) give the same order. They do here, because both sort by name, but a check proves it.

Example 7 — Refactor a churn summary script

Section titled “Example 7 — Refactor a churn summary script”

Goal: A script reports churn by contract type from data/customers.csv, plus two facts: how many customers churned in their first 6 months, and whether the file has brand-new customers. Refactor it with Counter, a comprehension, sum() and any(), and prove the output is unchanged.

Step 1 — Run the original and record its output

Section titled “Step 1 — Run the original and record its output”
def churn_before(path):
f = open(path)
lines = f.read().split("\n")
f.close()
header = lines[0].split(",")
data = []
for l in lines[1:]:
if l == "":
continue
data.append(l.split(","))
ci = header.index("contract")
chi = header.index("churned")
ti = header.index("tenure_months")
groups = {}
for d in data:
k = d[ci]
if not k in groups:
groups[k] = [0, 0]
groups[k][0] += 1
if d[chi] == "1":
groups[k][1] += 1
out = []
for k in sorted(groups.keys()):
rate = groups[k][1] / groups[k][0] * 100
out.append(k + ": " + str(groups[k][0]) + " customers, churn " + "%.1f" % rate + "%")
early = 0
for d in data:
if int(d[ti]) <= 6 and d[chi] == "1":
early = early + 1
has_new = False
for d in data:
if int(d[ti]) == 0:
has_new = True
break
out.append("Churned within 6 months: " + str(early))
out.append("Any brand-new customers: " + str(has_new))
return out
expected = churn_before("data/customers.csv")
print("\n".join(expected))
Output
month-to-month: 2784 customers, churn 29.6%
one-year: 1225 customers, churn 8.8%
two-year: 991 customers, churn 3.2%
Churned within 6 months: 488
Any brand-new customers: True

The function is about 40 lines long. Its names (ci, chi, d, k) say nothing. groups[k][0] and groups[k][1] hide “customers” and “churned” behind positions. The variable l is easy to confuse with 1; PEP 8 forbids it as a name.

churn.py (diff)
groups = {}
for d in data:
k = d[ci]
if not k in groups:
groups[k] = [0, 0]
groups[k][0] += 1
if d[chi] == "1":
groups[k][1] += 1
totals = Counter(c["contract"] for c in customers)
churned = Counter(c["contract"] for c in customers if c["churned"] == "1")

Two Counter objects replace the dict of two-item lists. Each has a name that says what it counts. A Counter returns 0 for a missing key, so a contract type with no churned customers needs no special case.

churn.py (diff)
early = 0
for d in data:
if int(d[ti]) <= 6 and d[chi] == "1":
early = early + 1
has_new = False
for d in data:
if int(d[ti]) == 0:
has_new = True
break
early = sum(int(c["tenure_months"]) <= 6 and c["churned"] == "1" for c in customers)
has_new = any(c["tenure_months"] == "0" for c in customers)

sum() of a generator of booleans counts the True values. any() replaces the flag variable and the break: it stops at the first match too.

Step 4 — Run the refactored version and compare

Section titled “Step 4 — Run the refactored version and compare”
def churn_after(path: Path) -> list[str]:
"""Return churn lines per contract type and two summary lines."""
with path.open(newline="", encoding="utf-8") as f:
customers = list(csv.DictReader(f))
totals = Counter(c["contract"] for c in customers)
churned = Counter(c["contract"] for c in customers if c["churned"] == "1")
lines = [
f"{contract}: {count} customers, churn {churned[contract] / count:.1%}"
for contract, count in sorted(totals.items())
]
early = sum(
int(c["tenure_months"]) <= 6 and c["churned"] == "1" for c in customers
)
has_new = any(c["tenure_months"] == "0" for c in customers)
lines.append(f"Churned within 6 months: {early}")
lines.append(f"Any brand-new customers: {has_new}")
return lines
after = churn_after(Path("data/customers.csv"))
print(after == expected)
assert after == expected
Output
True

The new function is half as long and reads top to bottom like the report it builds. The format spec :.1% multiplies by 100 and adds the percent sign, so rate * 100 and "%.1f" % rate + "%" go. The check proves that the percentages round the same way.

Common mistakes:

  • Writing churned[contract] / totals[contract] * 100 and then :.1%. The % spec multiplies by 100 again, and 29.6% becomes 2956.2%.
  • Using dict instead of Counter for churned and then churned[contract]. A contract type with no churned customers raises a KeyError.
  • Reading the file with split("\n") and split(","). It breaks on quoted fields and leaves an empty last line, which the original had to skip by hand.
Mistake Symptom Fix
def f(x, seen=[]): Results from earlier calls appear in later ones Default to None; create the list inside
lambda t: t > limit built in a loop Every function uses the last loop value Bind early: lambda t, limit=limit: ..., or a factory function
status is "fail" or count is 1000 False for equal values; SyntaxWarning for literals Use ==; keep is for None, True, False
value == float("nan") Always False math.isnan(value); in pandas .isna()
total == 672.3 on a computed float False for a correct result math.isclose(total, 672.3)
math.isclose(x, 0.0) False even for 5.5e-17 Add abs_tol=1e-9
round(2.675, 2) for money 2.67, not 2.68 Decimal("2.675").quantize(Decimal("0.01"), ROUND_HALF_UP)
Decimal(0.1) 0.1000000000000000055511... Build from a string: Decimal("0.1")
Decimal("1.5") * 0.9 TypeError: unsupported operand type(s) Convert both sides to Decimal
list.remove() inside for x in list Some items are skipped silently Build a new list with a comprehension
Deleting dict keys inside for k in d RuntimeError: dictionary changed size during iteration Loop over list(d), or build a new dict
zip(ids, values) on columns of different length Extra items are dropped silently zip(ids, values, strict=True)
all(check(x) for x in rows) on empty data True: the check passes with no data Also check rows (or len(rows))
next(x for x in rows if ...) with no match StopIteration next((x for x in rows if ...), None)
except: around a parse Typos and Ctrl+C are swallowed too except ValueError: around the one line that can fail
Trusting str.isdigit() before float() "²" passes the check and crashes float() Try float() and catch ValueError
[print(x) for x in rows] A list of None built for nothing Use a for loop for side effects
if len(rows) == 0: / if flag == True: Works; ruff reports E712 for the second if not rows: / if flag:
ruff check --fix --unsafe-fixes without review Behavior changes slip in Preview with --diff first
Cleaning up output formats during a refactor A report changes and nobody notices Record the old output and compare after each step
  • Web development: web frameworks such as Django and FastAPI read optional request fields with dict.get() and use EAFP to parse user input. A mutable default in a request handler leaks data between users, which is a security bug, not just a wrong number.
  • Automation and scripting: backup, deploy and file-renaming scripts use pathlib, with and any()/all() checks. Changing a list of files while you loop over it is a classic way to skip files.
  • Tooling and teams: almost every modern Python project runs ruff check and ruff format --check in continuous integration and in a pre-commit hook, a script that runs before each commit. A pull request (a proposed change to a shared repository) with lint errors is blocked when the project requires the check.
  • Finance and billing: payment, invoicing and tax code uses Decimal with an explicit rounding rule, because a one-cent difference breaks reconciliation with the bank.
  • Pythonic code uses the language’s idioms: loop over items directly, enumerate() for a count, zip(strict=True) for parallel data, items() for dicts, unpacking instead of indexes.
  • For dicts: get() for optional keys, get(k, 0) + 1 to count, setdefault(k, []).append(v) to group. Counter and defaultdict when counting or grouping is the main job.
  • Comprehensions build collections. Generator expressions feed sum(), any(), all(), min(), max() and join() without building a list. Use loops for side effects.
  • any([]) is False and all([]) is True. Check for empty data before you trust all().
  • EAFP tries the operation and catches the specific exception; LBYL checks first. Prefer EAFP for parsing and file access, LBYL for cheap checks and business rules, and dict.get() for optional keys.
  • PEP 8: snake_case for functions and variables, PascalCase for classes, UPPER_CASE for constants, is None, if not rows:, imports at the top in three groups.
  • Ruff lints (ruff check) and formats (ruff format). Rule codes name the problem; --fix applies safe fixes; --diff previews. Ruff finds patterns, not design.
  • Five gotchas: defaults are evaluated once; closures look up variables late; is tests identity, not value; floats are approximate (use math.isclose(), math.fsum(), Decimal); never change a list while you loop over it.
  • Refactor in small steps behind a characterization check: record the old output, change one thing, compare.

Q1. Rewrite for i in range(len(ids)): print(ids[i], temps[i]) in Pythonic style. What does strict=True add?

Answer

for sensor_id, temp in zip(ids, temps, strict=True): print(sensor_id, temp). Without strict=True, zip() stops at the shorter list and drops the extra items silently. With it, zip() raises a ValueError when the lengths differ, so a lost reading cannot go unnoticed.

Q2. What do counts.get("warn", 0) and groups.setdefault("S1", []) return when the key is missing? Which one changes the dict?

Answer

get() returns 0 and leaves the dict unchanged. setdefault() inserts "S1": [] and returns that new list, so a following .append(v) adds to the list inside the dict.

Q3. A validation step runs all(0 <= q <= 50 for q in quantities). Today’s file is empty. What is the result, and why is it a problem?

Answer

True. all() of an empty iterable is True (vacuous truth), so the check passes with no data at all. Combine it with a count check: quantities and all(...), or fail explicitly when not quantities.

Q4. Explain EAFP and LBYL in one sentence each. Give one case where LBYL is the better choice.

Answer

EAFP tries the operation and handles the exception if it fails. LBYL checks that the operation can succeed before it runs it. LBYL is better when the failure is common and the check is cheap and exact, such as skipping blank lines with if not line.strip(): continue, or when the check is a business rule such as if quantity > MAX_QUANTITY.

Q5. What does this print, and why? How do you fix it?

def add_tag(tag, tags=[]):
tags.append(tag)
return tags
add_tag("vip")
print(add_tag("new"))
Answer

It prints ['vip', 'new']. The default list is created once, when Python runs the def, and every call without a tags argument shares it. Fix: def add_tag(tag, tags=None): and then if tags is None: tags = [] inside the function.

Q6. A loop builds checks.append(lambda t: t > limit) for the limits 23, 25 and 27. Why does every check compare with 27? Give two fixes.

Answer

The lambda remembers the variable limit, not its value, and looks it up when it runs (late binding). By then the loop has finished and limit is 27. Fixes: bind the value as a default, lambda t, limit=limit: t > limit, or build each check with a factory function such as make_check(limit).

Q7. When should you use is instead of ==? Why can a is b be True for 256 and False for 20228?

Answer

Use is only for singletons: None, True and False. Use == for every value comparison. CPython keeps one shared object for each integer from -5 to 256, so two computed 256 values are the same object. Larger integers are new objects each time. This is an implementation detail; code must not depend on it.

Q8. Why is round(129.95 * 0.9, 2) 116.95 and not 116.96? Write the Decimal version that follows “round half up”.

Answer

The float result is stored as slightly less than 116.955, so it rounds down. (Decimal("129.95") * Decimal("0.9")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) gives Decimal('116.96'), because Decimal stores the exact value 116.955.

Q9. What does this print, and what is the Pythonic fix?

codes = [-999.0, -999.0, 21.4]
for c in codes:
if c == -999.0:
codes.remove(c)
print(codes)
Answer

It prints [-999.0, 21.4]. Removing the first item shifts the second -999.0 into position 0, and the loop moves on to position 1, so it never checks it. Fix: codes = [c for c in codes if c != -999.0].

Q10. Ruff reports E722, F401 and B006. What does each family letter mean, and which of the three is a likely bug?

Answer

E is pycodestyle (PEP 8 style), F is Pyflakes (real errors such as unused imports and undefined names) and B is flake8-bugbear (likely bugs). E722 is a bare except, F401 an unused import and B006 a mutable default argument. B006 and E722 are likely bugs; F401 is dead code.

Q11. What is a characterization test, and why do you record the output before you refactor?

Answer

It is a check that records what the existing code does now, right or wrong, so that you can prove a change did not alter it. You record it first because after the change, the old behavior is gone and you have nothing to compare with.

Your progress

0 / 4 done

  • Exercises: 26 exercises with hints and full solutions: idioms, EAFP and LBYL, gotchas, ruff findings and refactors.
  • Mini-project: refactor a legacy sales-cleaning script into clean, ruff-checked code with the same output.
  • Cheat sheet: every idiom, PEP 8 rule, ruff command and gotcha of this module on one page.
  • Next module: 14. Testing with pytest turns the characterization checks of this module into automated tests.