Recipe 12.2 · Python
Source-Generated Serialization
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
Reflection-based serialization is fast once warmed up, but the first call for each type pays to build its metadata. In a serverless function, a command-line tool or a container that scales from zero, that start-up cost shows up on every cold start. Trimmed and native AOT builds go further and cannot use reflection-based serialization at all.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Nothing is wrong with this code in a long-running web app. It becomes a problem when start-up time matters or when you publish with trimming, where the linker removes the members the serializer was going to discover at runtime.
Requirements: Python 3.12+. Install: pip install pydantic
"""Serialize and deserialize an order with default, runtime-reflected settings
Source: ImproveCode, Chapter 12, Recipe 12.2 "Source-Generated Serialization"
Section: The way it's often written
Book page: 259 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
JsonSerializer reflection -> a fresh pydantic TypeAdapter built on each call
(schema is rebuilt every time, the analogue of reflection warm-up).
"""
# Not to copy: reflection at runtime, warm-up on every cold start
from typing import Any
from pydantic import TypeAdapter
def round_trip(order: Any, order_type: type) -> Any:
json = TypeAdapter(order_type).dump_json(order).decode()
copy = TypeAdapter(order_type | None).validate_json(json)
return copy
The improved recipe
Declare a JsonSerializerContext and list the types you serialize. The compiler generates the
metadata and the fast-path serialization code at build time.
Requirements: Python 3.12+. Install: pip install pydantic
"""Precompiled serialization context for Order and list[Order]
Source: ImproveCode, Chapter 12, Recipe 12.2 "Source-Generated Serialization"
Section: The improved recipe
Book page: 259-260 -- original C# listing
Converted from C# to Python.
Python has no source generators; the closest equivalent is building pydantic
TypeAdapters once at import time (schema compiled ahead of first use) with
Web-style settings: camelCase aliases (declared on the model), nulls omitted,
enums as strings.
"""
from __future__ import annotations
from typing import Any
from pydantic import TypeAdapter
from p256_r12_1_order_model_types import Order
class _Adapter:
"""A TypeAdapter bundled with the write options (WhenWritingNull)."""
def __init__(self, tp: Any) -> None:
self.adapter: TypeAdapter[Any] = TypeAdapter(tp)
def dump(self, value: Any) -> str:
return self.adapter.dump_json(
value, by_alias=True, exclude_none=True).decode()
def load(self, json: str) -> Any:
return self.adapter.validate_json(json)
class AppJsonContext:
"""Equivalent of the source-generated JsonSerializerContext."""
order = _Adapter(Order)
list_order = _Adapter(list[Order])
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Typed Order JSON helpers that go through the precompiled context
Source: ImproveCode, Chapter 12, Recipe 12.2 "Source-Generated Serialization"
Section: The improved recipe
Book page: 260 -- original C# listing
Converted from C# to Python.
AppJsonContext.Default.Order / ListOrder -> the prebuilt adapters from p259.
"""
from __future__ import annotations
from p256_r12_1_order_model_types import Order
from p259_r12_2_precompiled_json_context import AppJsonContext
class OrderJson:
@staticmethod
def serialize(order: Order) -> str:
return AppJsonContext.order.dump(order)
@staticmethod
def deserialize(json: str) -> Order | None:
return AppJsonContext.order.load(json)
@staticmethod
def deserialize_list(json: str) -> list[Order] | None:
return AppJsonContext.list_order.load(json)
How it works
The [JsonSerializable] attributes tell the source generator which root types to handle. It walks
each type's properties, generates a JsonTypeInfo<T> for every type it finds, and exposes them as
properties on AppJsonContext.Default: Order, ListOrder, OrderLine and so on. Passing a
JsonTypeInfo<T> to Serialize or Deserialize skips reflection completely.
[JsonSourceGenerationOptions] carries the settings. Starting from JsonSerializerDefaults.Web
and adding UseStringEnumConverter gives you the same wire format as JsonDefaults.Web from the
previous recipe, so the two can read each other's output.
Because the code is generated at compile time, you can open it. In Visual Studio expand
Dependencies, Analyzers, System.Text.Json.SourceGeneration. It is ordinary C#, which also makes
serialization bugs easier to step through.
Variations and pitfalls
- The class must be
partial. The generator fills in the other half. Forget the keyword and you get a compile error that points at the generator, not at your class. - Missing types fail at runtime. If you serialize a type the context does not list, you get a
NotSupportedExceptionor, worse, a silent fallback to reflection. In the project file, set<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>so the fallback is off and the mistake shows up in your first test. - ASP.NET Core. Register the context with minimal APIs so request and response bodies use it:
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default)); - Combining with shared options. If you want
JsonDefaultsand the generated metadata together, createnew JsonSerializerOptions(JsonDefaults.Web) { TypeInfoResolver = AppJsonContext.Default }once and keep it in a static field. - When not to bother. For an internal line-of-business web app that starts once a day, the gain is small. Use source generation for cold-start-sensitive hosts, trimmed or AOT publishing, and the few hot paths a profiler points at.