Recipe 8.1 · Python
Guard Clauses with the Built-in Throw Helpers
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Public methods receive arguments they cannot work with: a null dependency, an empty customer ID, a negative amount. Without a check, the method fails later with a NullReferenceException or, worse, writes bad data. With hand-written checks, every method starts with six lines of if and throw, and the parameter names in the messages drift out of date when someone renames a parameter.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Three problems show up here. The parameter name in the first exception is wrong because the parameter was renamed years ago. The second check throws a bare Exception, so callers cannot tell an argument problem from a database outage. And whitespace-only IDs pass straight through.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Hand-written, inconsistent argument checks
Source: ImproveCode, Chapter 8, Recipe 8.1 "Guard Clauses with the Built-in Throw Helpers"
Section: The way it's often written
Book page: 163 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
ArgumentNullException/ArgumentException map to TypeError/ValueError; the elided body stays elided.
"""
from decimal import Decimal
from typing import Any
def create_invoice(customer_id: str | None, amount: Decimal,
terms_days: int) -> Any:
if customer_id is None:
raise TypeError("custId")
if customer_id == "":
raise Exception("Customer is required")
if amount <= 0:
raise ValueError("bad amount")
# termsDays never checked
...
The improved recipe
Since .NET 6, and much more so in .NET 8, the exception types themselves carry static throw helpers. They use CallerArgumentExpression to fill in the parameter name for you, so a rename can never make the message lie. For the few checks the framework does not cover, a small Guard class follows the same pattern.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Guard helpers and an invoice factory that validates every argument
Source: ImproveCode, Chapter 8, Recipe 8.1 "Guard Clauses with the Built-in Throw Helpers"
Section: The improved recipe
Book page: 163-165 -- original C# listing
Converted from C# to Python.
Python has no CallerArgumentExpression, so guards take an explicit param_name;
ArgumentOutOfRangeException maps to ValueError; TimeProvider becomes a clock callable.
"""
from collections.abc import Callable, Collection
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
from enum import Enum
from typing import TypeVar
T = TypeVar("T")
E = TypeVar("E", bound=Enum)
class Guard:
@staticmethod
def not_empty(value: Collection[T] | None, param_name: str) -> Collection[T]:
if value is None:
raise TypeError(f"{param_name} must not be None.")
if len(value) == 0:
raise ValueError(
f"The collection must contain at least one item. ({param_name})")
return value
@staticmethod
def defined(value: object, enum_type: type[E], param_name: str) -> E:
if not isinstance(value, enum_type):
raise ValueError(
f"{param_name}: {value!r} is not a defined {enum_type.__name__}.")
return value
class PaymentTerms(Enum):
NET15 = 15
NET30 = 30
NET60 = 60
@dataclass(frozen=True)
class InvoiceDraft:
customer_id: str
amount: Decimal
terms: PaymentTerms
lines: Collection[str]
class InvoiceFactory:
def __init__(self, clock: Callable[[], datetime]) -> None:
if clock is None:
raise TypeError("clock must not be None.")
self._clock = clock
def create(self, customer_id: str, amount: Decimal,
terms: PaymentTerms, lines: Collection[str]) -> InvoiceDraft:
if customer_id is None or not customer_id.strip():
raise ValueError("customer_id must not be null or whitespace.")
if amount <= 0:
raise ValueError("amount must be greater than zero.")
if amount > Decimal("1000000"):
raise ValueError("amount must be 1,000,000 or less.")
Guard.defined(terms, PaymentTerms, "terms")
Guard.not_empty(lines, "lines")
return InvoiceDraft(customer_id.strip(), amount, terms, lines)
def due_date(self, terms: PaymentTerms) -> date:
Guard.defined(terms, PaymentTerms, "terms")
today = self._clock().astimezone(timezone.utc).date()
return today + timedelta(days=terms.value)
# Usage: InvoiceFactory(lambda: datetime.now(timezone.utc))
How it works
ArgumentNullException.ThrowIfNull and ArgumentException.ThrowIfNullOrWhiteSpace take the argument and nothing else. The compiler passes the text of the argument expression, so the exception says customerId, not a string someone typed. ArgumentOutOfRangeException gained a family of generic helpers in .NET 8: ThrowIfNegative, ThrowIfZero, ThrowIfNegativeOrZero, ThrowIfGreaterThan, ThrowIfLessThan, ThrowIfEqual and their siblings. They work for any numeric type, including decimal, and the message includes the actual value, which saves a trip to the debugger.
The Guard class covers two gaps I hit often: an empty collection, and an enum value that is not one of the named members. Casting any integer to an enum compiles, so (PaymentTerms)7 is a perfectly legal value until it reaches a switch. Enum.IsDefined<TEnum> is the generic overload, with no boxing. Both guard methods return the value, so you can use them inline in a constructor assignment if you like.
The throw helpers are also cheap. The throwing path lives in a separate method that the JIT does not inline, so the happy path is a compare and a branch.
Variations and pitfalls
- Guards are for programmer errors. A guard clause says "the caller broke the contract." It is not how you tell a user that the e-mail field is blank. User input goes through the validators in the next recipes and comes back as a list of messages, not an exception.
- Don't guard private methods to death. Check at public and protected entry points. Inside a class, trust your own code and let nullable reference types do the work.
- Flags enums need a different check.
Enum.IsDefinedreturns false for combined flag values such asRead | Write. For[Flags]enums, compare against a mask of all valid bits instead. - Keep the old package away. Several third-party "Guard" packages predate these helpers. In new code the built-in ones are enough, and they need no dependency.
On .NET Framework
CallerArgumentExpression is a compiler feature, so it works on .NET Framework 4.8 with C# 10 or later if you declare the attribute class yourself (in the System.Runtime.CompilerServices namespace). The static throw helpers do not exist there. Put equivalents in your own Guard class with the same names, and the call sites will move to .NET 8 unchanged.