DEV Community

Cover image for None Means Clear, Missing Means Keep: PATCH Use Cases With Python 3.15's sentinel
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

None Means Clear, Missing Means Keep: PATCH Use Cases With Python 3.15's sentinel


A user opens their settings page, deletes the text in the bio box and clicks Save. The client sends {"bio": null}. The server answers 200. The bio is still there.

You have probably written the handler that does this. The request model says bio: str | None = None, and the update code says if body.bio is not None: profile.bio = body.bio. Omitting bio and sending null produce the same Python value, so the handler cannot tell "leave it alone" from "clear it". Flip the code to profile.bio = body.bio and you get the opposite bug: every PATCH that leaves bio out wipes it.

JSON Merge Patch (RFC 7396) is explicit about the contract: "Null values in the merge patch are given special meaning to indicate the removal of existing values in the target", and members you leave out stay untouched. So each field in a PATCH body has three states, and Optional[str] = None only has two.

Python 3.15, released on 9 October 2026, ships a built-in for the third state, and it fits in a use case that never sees the HTTP framework.

Three states, one type: the sentinel built-in

PEP 661 was accepted in April 2026 and adds sentinel to the builtins. The 3.15 docs give the signature as sentinel(name, /, *, repr=None). You call it once, at module level, and assign it to a variable with the same name:

KEEP = sentinel("KEEP")
Enter fullscreen mode Exit fullscreen mode

The old idiom was _MISSING = object(). The PEP's motivation section lists what goes wrong with it: an "uninformative and overly verbose repr", no distinct type for signatures, and copies that "behave unexpectedly after being copied, due to a separate instance being created". The new built-in fixes all three, per the docs:

  • repr(KEEP) is KEEP.
  • Shallow and deep copies return the object itself.
  • Pickling works when the sentinel lives at module level under a matching name, and the unpickled value is the original.
  • It works in type expressions with |, so str | None | KEEP is a valid annotation.

Two details matter for PATCH code. Sentinels are truthy and compare equal only to themselves, so the docs tell you to compare with is. And the PEP asks type checkers to narrow a union on is / is not, the same way they narrow None. The PEP also asks checkers to flag a sentinel whose string name does not match its variable name, which is why the name appears twice.

A three-position switch whose positions are marked with an open lock, an eraser and a pen
Each PATCH field has three positions: keep, clear, set.

The domain: a command with three states per field

The core of the app is a frozen Profile and a frozen UpdateProfile command. Every optional field on the command defaults to KEEP:

# profiles/domain.py
from dataclasses import dataclass

KEEP = sentinel("KEEP")

@dataclass(frozen=True)
class Profile:
    user_id: str
    display_name: str
    bio: str | None
    website: str | None

@dataclass(frozen=True)
class UpdateProfile:
    user_id: str
    display_name: str | KEEP = KEEP
    bio: str | None | KEEP = KEEP
    website: str | None | KEEP = KEEP
Enter fullscreen mode Exit fullscreen mode

Read the annotations as the API contract. display_name can be kept or replaced but never cleared, because None is not in its type. bio and website accept all three states. Nothing in this file imports FastAPI or Pydantic, and a dataclass default of KEEP is fine because the sentinel is hashable, which is the check dataclasses use to reject mutable defaults.

The use case applies only what was sent

The port is a Protocol, and the handler builds a change set by skipping every field that is still KEEP:

# profiles/use_cases.py
from dataclasses import fields, replace
from typing import Protocol

from profiles.domain import KEEP, Profile, UpdateProfile

class ProfileNotFound(Exception):
    pass

class ProfileRepository(Protocol):
    async def get(self, user_id: str) -> Profile | None: ...
    async def save(self, profile: Profile) -> None: ...

class UpdateProfileHandler:
    def __init__(self, repo: ProfileRepository) -> None:
        self._repo = repo

    async def __call__(self, cmd: UpdateProfile) -> Profile:
        current = await self._repo.get(cmd.user_id)
        if current is None:
            raise ProfileNotFound(cmd.user_id)
        changes = {}
        for f in fields(cmd):
            value = getattr(cmd, f.name)
            if f.name != "user_id" and value is not KEEP:
                changes[f.name] = value
        updated = replace(current, **changes)
        await self._repo.save(updated)
        return updated
Enter fullscreen mode Exit fullscreen mode

None passes the is not KEEP check, so bio=None lands in changes and clears the field. An omitted field never reaches replace, so the stored value survives. If you prefer the type checker to see each branch, write one if cmd.bio is not KEEP: per field instead of the loop. With three fields, either is fine.

For tests, an in-memory adapter satisfies the port:

# profiles/memory.py
from profiles.domain import Profile

class InMemoryProfiles:
    def __init__(self, *profiles: Profile) -> None:
        self.rows = {p.user_id: p for p in profiles}

    async def get(self, user_id: str) -> Profile | None:
        return self.rows.get(user_id)

    async def save(self, profile: Profile) -> None:
        self.rows[profile.user_id] = profile
Enter fullscreen mode Exit fullscreen mode

The FastAPI adapter reads model_fields_set

A hexagon with a plain command card inside it and a request form outside it, joined by a single arrow
The request model stays outside the hexagon; only the command crosses in.

Pydantic already tracks which fields the client sent. The API reference describes model_fields_set as "the set of fields that have been explicitly set on this model instance", and a field sent as null counts as set. The adapter turns that set into the command:

# profiles/http.py
from dataclasses import asdict

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ConfigDict, field_validator

from profiles.domain import UpdateProfile
from profiles.use_cases import (
    ProfileNotFound,
    ProfileRepository,
    UpdateProfileHandler,
)

class ProfilePatch(BaseModel):
    model_config = ConfigDict(extra="forbid")

    display_name: str | None = None
    bio: str | None = None
    website: str | None = None

    @field_validator("display_name")
    @classmethod
    def no_null_name(cls, v: str | None) -> str | None:
        if v is None:
            raise ValueError("display_name cannot be null")
        return v

    def to_command(self, user_id: str) -> UpdateProfile:
        sent = {n: getattr(self, n) for n in self.model_fields_set}
        return UpdateProfile(user_id=user_id, **sent)
Enter fullscreen mode Exit fullscreen mode

to_command is the whole translation: only the keys the client sent become arguments, so everything else stays KEEP. The same file then wires the route:

# profiles/http.py (continued)
def create_app(repo: ProfileRepository) -> FastAPI:
    app = FastAPI()
    handler = UpdateProfileHandler(repo)

    @app.patch("/profiles/{user_id}")
    async def patch_profile(
        user_id: str, body: ProfilePatch
    ) -> dict[str, str | None]:
        try:
            profile = await handler(body.to_command(user_id))
        except ProfileNotFound:
            raise HTTPException(status_code=404)
        return asdict(profile)

    return app
Enter fullscreen mode Exit fullscreen mode

extra="forbid" turns a typo like {"boi": null} into a 422 instead of a 200 that silently changes nothing, and it guarantees **sent only carries names the command declares. The validator rejects {"display_name": null} with a 422, and because Pydantic does not validate defaults unless you set validate_default, an omitted display_name never reaches it. And create_app(repo) is the composition root: production passes a SQLAlchemy repository, tests pass the in-memory one.

The FastAPI body-updates tutorial solves the same problem with item.model_dump(exclude_unset=True) and model_copy(update=...). That works when the stored object is a Pydantic model. Here the core receives a typed command instead of a loose dict[str, Any], and the domain has no Pydantic import to remove later.

Pydantic 2.14, released on 8 October 2026, added Python 3.15 support and stabilised its own MISSING sentinel for fields, written timeout: int | None | MISSING = MISSING. That is a reasonable way to declare the request model. Keep it in the adapter: pydantic.MISSING in the domain would put the framework back in the core, which is the coupling this layout exists to avoid.

pytest for all three states

The core tests need no web client and no pytest plugin. asyncio.run drives the async handler from a plain def test:

# tests/test_update_profile.py
import asyncio
import copy
import pickle

from profiles.domain import KEEP, Profile, UpdateProfile
from profiles.memory import InMemoryProfiles
from profiles.use_cases import UpdateProfileHandler

ADA = Profile("u1", "Ada", bio="Engines", website=None)

def run(cmd: UpdateProfile) -> Profile:
    handler = UpdateProfileHandler(InMemoryProfiles(ADA))
    return asyncio.run(handler(cmd))

def test_omitted_field_is_kept():
    assert run(UpdateProfile("u1")).bio == "Engines"

def test_none_clears_the_field():
    assert run(UpdateProfile("u1", bio=None)).bio is None

def test_value_replaces_only_that_field():
    out = run(UpdateProfile("u1", bio="Looms"))
    assert out.bio == "Looms"
    assert out.display_name == "Ada"

def test_keep_survives_copy_and_pickle():
    assert copy.deepcopy(KEEP) is KEEP
    assert pickle.loads(pickle.dumps(KEEP)) is KEEP
Enter fullscreen mode Exit fullscreen mode

The last test is the one object() could not reliably pass. It matters the day a command gets deep-copied in a test fixture or pickled onto a worker queue.

The adapter tests go through HTTP. FastAPI's testing guide notes that TestClient needs httpx installed and that tests stay plain def:

# tests/test_http.py
import pytest
from fastapi.testclient import TestClient

from profiles.domain import Profile
from profiles.http import create_app
from profiles.memory import InMemoryProfiles

ADA = Profile("u1", "Ada", bio="Engines", website=None)

@pytest.mark.parametrize(
    ("body", "expected_bio"),
    [
        ({}, "Engines"),
        ({"bio": None}, None),
        ({"bio": "Looms"}, "Looms"),
    ],
)
def test_patch_bio(body, expected_bio):
    repo = InMemoryProfiles(ADA)
    http = TestClient(create_app(repo))
    resp = http.patch("/profiles/u1", json=body)
    assert resp.status_code == 200
    assert repo.rows["u1"].bio == expected_bio

def test_null_display_name_is_422():
    http = TestClient(create_app(InMemoryProfiles(ADA)))
    resp = http.patch("/profiles/u1", json={"display_name": None})
    assert resp.status_code == 422
Enter fullscreen mode Exit fullscreen mode

The three parametrized rows are the whole contract from RFC 7396: missing keeps, null clears, a value replaces. If someone later "simplifies" to_command or the handler back to an is not None check, the middle row fails.

Where the sentinel stops

The sentinel belongs in the command and the use case, and nowhere past them. The repository receives a finished Profile with real values, so the SQLAlchemy adapter never has to know KEEP exists. The response is built from that Profile, so the sentinel never reaches JSON either.

An empty body {} is valid here and returns the profile unchanged; if your API should reject it, check model_fields_set for emptiness in the adapter. The built-in is new in 3.15 (What's New), so this exact code needs a 3.15 interpreter. On older versions you are back to a hand-rolled sentinel and the copy and pickle caveats above.


If this was useful

The split in this post, Pydantic and FastAPI at the edge and a plain command plus use case in the middle, is the core idea of Hexagonal Architecture in Python. The book builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered, vertical slice) and then measures the trade-offs, so you can see where a boundary like this one pays for itself. Every listing runs from the free companion repo.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (0)