Recipe 15.1 · Python
Extension Methods Worth Keeping
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
Extension methods are easy to write and hard to remove. Teams collect dozens of them, many duplicating what the base class library already does. A few, though, remove real noise from everyday code and prevent real bugs. You want a small set you can carry from project to project, and a rule for saying no to the rest.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Each of these looks harmless. IsEmpty treats a string of spaces as valid input. ToInt turns "12,5", "abc" and null into zero without a trace. And because ToInt extends object, it shows up in IntelliSense on every variable in the solution.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Grab-bag string/object helpers that hide surprises and swallow errors
Source: ImproveCode, Chapter 15, Recipe 15.1 "Extension Methods Worth Keeping"
Section: The way it's often written
Book page: 326 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
C# extension methods become plain module-level functions; Convert.ToInt32 becomes int().
"""
# Not to copy: wrappers, surprises and swallowed errors.
def is_empty(s: str | None) -> bool:
return s is None or s == "" # misses " "
def to_int(o: object) -> int:
try:
return int(o) # type: ignore[call-overload]
except Exception:
return 0 # bad data becomes 0
def in_(s: str, *items: str) -> bool:
return s in items # case-sensitive?
The improved recipe
Usage snippet:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""A small set of null-safe string and collection helpers worth keeping
Source: ImproveCode, Chapter 15, Recipe 15.1 "Extension Methods Worth Keeping"
Section: The improved recipe
Book page: 326-327 -- original C# listing
Converted from C# to Python.
Extension methods become module functions. Python dicts take no IEqualityComparer, so
to_dict_first_wins accepts an optional key_normalizer (e.g. str.casefold) instead;
OrdinalIgnoreCase comparison is approximated with str.casefold().
"""
from __future__ import annotations
from collections.abc import Callable, Hashable, Iterable
def has_text(value: str | None) -> bool:
return value is not None and value.strip() != ""
def trim_to_null(value: str | None) -> str | None:
if value is None:
return None
trimmed = value.strip()
return None if len(trimmed) == 0 else trimmed
def equals_ignore_case(value: str | None, other: str | None) -> bool:
if value is None or other is None:
return value is other
return value.casefold() == other.casefold()
def empty_if_null[T](source: Iterable[T] | None) -> Iterable[T]:
return source if source is not None else ()
def where_not_null[T](source: Iterable[T | None]) -> Iterable[T]:
return (item for item in source if item is not None)
def to_dict_first_wins[K: Hashable, T](
source: Iterable[T],
key_selector: Callable[[T], K],
key_normalizer: Callable[[K], K] | None = None,
) -> dict[K, T]:
if source is None:
raise TypeError("source must not be None")
if key_selector is None:
raise TypeError("key_selector must not be None")
result: dict[K, T] = {}
for item in source:
key = key_selector(item)
if key_normalizer is not None:
key = key_normalizer(key)
result.setdefault(key, item) # first one wins, like TryAdd
return result
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Using the trim/has-text/first-wins dictionary helpers at a call site
Source: ImproveCode, Chapter 15, Recipe 15.1 "Extension Methods Worth Keeping"
Section: The improved recipe
Book page: 327 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; StringComparer.OrdinalIgnoreCase becomes a
str.casefold key normalizer.
"""
from collections.abc import Callable, Iterable
from typing import Any
from p326_r15_1_common_extension_helpers import has_text, to_dict_first_wins, trim_to_null
def example(form: Any, customer: Any, products: Iterable[Any], send: Callable[[str], None]) -> None:
note: str | None = trim_to_null(form.note) # "" and " " -> None
if has_text(customer.email):
send(customer.email) # type checker knows it's not None
by_code = to_dict_first_wins(products, lambda p: p.code, str.casefold)
_ = (note, by_code)
How it works
HasText replaces the most common two-line check in business code and carries the [NotNullWhen(true)] attribute, so the compiler knows the string is not null inside the if. With nullable reference types on, that removes a whole category of ! operators.
TrimToNull normalizes form input at the boundary. Empty strings and whitespace become null, which is what you want to store in a nullable column. A database full of '', ' ' and NULL all meaning "no value" makes every later query harder.
EqualsIgnoreCase makes the comparison explicit. Ordinal comparison is the right default for codes, keys, file extensions and anything a machine produced. Culture-aware comparison is for sorting names shown to people.
EmptyIfNull lets a foreach run over a collection property that might be null, and WhereNotNull filters nulls while giving you a non-nullable element type. OfType<T>() already skips nulls, so the method is one line; the name just says what you mean.
ToDictionaryFirstWins exists because of a crash that turns up in a lot of codebases: ToDictionary throws "An item with the same key has already been added" the first time real data contains a duplicate. When duplicates are possible and the first row is the right one, say so in the method name.
Variations and pitfalls
- My rule for a new extension method: it must remove noise in at least three places, it must not hide a failure, and it must not extend
object. Most proposed extensions fail the first test. - Check the BCL before writing one.
Chunk,DistinctBy,MaxBy,GetValueOrDefault,TryAdd,string.JoinandEnumerable.ToHashSetreplaced a lot of homegrown helpers between .NET Core 2.0 and .NET 6. - Don't put extension methods in the
Systemnamespace to make them appear everywhere. Put them in your own namespace and import it where needed. - If
ToDictionaryFirstWinshides data quality problems you should fix, log the duplicates instead of silently dropping them.