IC Improve Code Recipes

Recipe 15.5 · Python

Safe Parsing and Conversion

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

Values arrive as strings from query strings, CSV files, config and old database columns. The code converts them with int.Parse, Convert.ToDecimal or a try/catch helper. Bad input either crashes the request or turns silently into zero. And on a server with a different regional setting, "1,5" and "1.5" swap meaning.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Parsing helpers that use exceptions for control flow and the current culture (p338_r15_5_exception_based_parsing_before.py)
"""Parsing helpers that use exceptions for control flow and the current culture

Source: ImproveCode, Chapter 15, Recipe 15.5 "Safe Parsing and Conversion"
Section: The way it's often written
Book page: 338-339  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
DBNull.Value becomes None; culture-dependent Convert.ToDecimal becomes locale.delocalize.
"""

import locale
from decimal import Decimal

# Not to copy: exceptions for control flow, culture-dependent.


def get_int(s: str) -> int:
    try:
        return int(s)
    except Exception:
        return 0


def get_decimal(o: object) -> Decimal:
    if o is None:
        return Decimal(0)
    return Decimal(locale.delocalize(str(o)))  # uses the current locale

The improved recipe

Usage snippet:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Culture-invariant try-parse helpers that return None instead of throwing (p339_r15_5_safe_parse_helpers.py)
"""Culture-invariant try-parse helpers that return None instead of throwing

Source: ImproveCode, Chapter 15, Recipe 15.5 "Safe Parsing and Conversion"
Section: The improved recipe
Book page: 339-340  -- original C# listing
Converted from C# to Python.
IParsable<T> becomes a parser callable (e.g. uuid.UUID); NumberStyles rules are mirrored
with regexes so int("1_000") style quirks are rejected. Date formats are strptime
patterns (default "%Y-%m-%d") instead of .NET "yyyy-MM-dd" patterns.
"""

import re
from collections.abc import Callable
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from enum import Enum

_INTEGER = re.compile(r"\s*[+-]?[0-9]+\s*")
_NUMBER = re.compile(r"\s*[+-]?(?:[0-9][0-9,]*)?(?:\.[0-9]*)?\s*")


def value[T](text: str | None, parser: Callable[[str], T]) -> T | None:
    if text is None:
        return None
    try:
        return parser(text.strip())
    except (ValueError, TypeError, ArithmeticError):
        return None


def int_(text: str | None) -> int | None:
    if text is None or not _INTEGER.fullmatch(text):
        return None
    result = int(text)
    return result if -(2**31) <= result <= 2**31 - 1 else None


def decimal_(text: str | None) -> Decimal | None:
    if text is None or not _NUMBER.fullmatch(text):
        return None
    try:
        result = Decimal(text.strip().replace(",", ""))
    except InvalidOperation:
        return None
    return result if result.is_finite() else None


def date_(text: str | None, *formats: str) -> date | None:
    if text is None or not text.strip():
        return None

    accepted = formats if len(formats) > 0 else ("%Y-%m-%d",)

    for fmt in accepted:
        try:
            return datetime.strptime(text.strip(), fmt).date()
        except ValueError:
            continue
    return None


def bool_(text: str | None) -> bool | None:
    match text.strip().upper() if text is not None else None:
        case "TRUE" | "T" | "YES" | "Y" | "1" | "ON":
            return True
        case "FALSE" | "F" | "NO" | "N" | "0" | "OFF":
            return False
        case _:
            return None


def enum_value[E: Enum](text: str | None, enum_type: type[E]) -> E | None:
    if text is None:
        return None
    key = text.strip()
    for member in enum_type:
        if member.name.casefold() == key.casefold():
            return member
    try:
        return enum_type(int(key))  # numeric text, only if defined
    except (ValueError, TypeError):
        return None

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Use safe-parse helpers for a query-string page size, an import date and an id (p340_r15_5_safe_parse_usage.py)
"""Use safe-parse helpers for a query-string page size, an import date and an id

Source: ImproveCode, Chapter 15, Recipe 15.5 "Safe Parsing and Conversion"
Section: The improved recipe
Book page: 340  -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; "M/d/yyyy" becomes the strptime pattern "%m/%d/%Y"
and Guid becomes uuid.UUID.
"""

import uuid
from collections.abc import Mapping, Sequence

from p339_r15_5_safe_parse_helpers import date_, int_, value


def example(
    query: Mapping[str, str],
    row: Sequence[str],
    form: Mapping[str, str],
    errors: list[str],
    line_number: int,
) -> None:
    page_size = int_(query.get("size"))
    page_size = page_size if page_size is not None else 25

    ship_date = date_(row[4], "%Y-%m-%d", "%m/%d/%Y")
    if ship_date is None:
        errors.append(f"Line {line_number}: invalid ship date '{row[4]}'.")

    id_ = value(form.get("id"), uuid.UUID)
    _ = (page_size, id_)

How it works

Every method returns a nullable value. null means "could not parse", which is different from zero, and the caller decides what to do: use a default with ??, record a validation error, or reject the request. Nothing is swallowed and no exception is thrown for ordinary bad input, which matters in import loops where exceptions cost real time.

Value<T> uses the generic math interface IParsable<T> (.NET 7 and later). One method covers int, long, Guid, DateTime, TimeSpan and any of your own types that implement the interface.

Culture is explicit. Machine-produced text, such as files, query strings, config values and APIs, should be parsed with the invariant culture. Text that a person typed in a localized UI should be parsed with that person's culture, passed in as provider. The one thing never to do is depend on the server's current culture. Rebuild the server of a nightly import with a German locale and "1.250" stops meaning one and a quarter and starts meaning one thousand two hundred fifty.

Date uses TryParseExact with a list of formats you accept. Loose parsing of 03/04/2026 guesses between March 4 and April 3; exact formats don't guess.

EnumValue adds an Enum.IsDefined check, because Enum.TryParse accepts any number: "42" parses into an enum that has no member 42.

Variations and pitfalls

  • IsDefined returns false for combined [Flags] values. For flags enums, drop the check or validate against the mask of all defined bits.
  • For database values, avoid this class entirely. Read typed values with reader.GetInt32 or let Dapper map them, as in Chapter 1. DBNull handling belongs at the data boundary, not in a string parser.
  • If you need the reason a value failed, return a small result type (Chapter 5) instead of null.
  • ASP.NET Core model binding already parses route and query values into typed parameters with the invariant culture. Use SafeParse for the places binding doesn't reach: files, config strings, legacy columns that store numbers as text.