DEV Community

Cover image for A Frozen Dataclass With a dict Inside Isn't Frozen. Python 3.15's frozendict Is
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

A Frozen Dataclass With a dict Inside Isn't Frozen. Python 3.15's frozendict Is


You mark your domain event @dataclass(frozen=True), the code review says "nice, immutable", and it merges. A week later two things happen. A handler writes event.metadata["retry"] = "1" and every other subscriber now sees a retry flag that was never part of the event. And the outbox relay that dedupes events with a set crashes on the first event it touches, with TypeError: unhashable type: 'dict'.

Both bugs come from the same line: a dict field inside a frozen dataclass. The dataclasses docs are honest about it: "It is not possible to create truly immutable Python objects. However, by passing frozen=True to the @dataclass decorator you can emulate immutability." The emulation covers attribute assignment. It does nothing for the objects your attributes point at.

Python 3.15 was released on 9 October 2026, and it ships a built-in frozendict from PEP 814. That is the missing piece for value objects and domain events.

What frozen=True actually freezes

Here is the event as it usually gets written:

from dataclasses import dataclass, field
from datetime import datetime

@dataclass(frozen=True)
class OrderPlaced:
    order_id: str
    placed_at: datetime
    metadata: dict[str, str] = field(default_factory=dict)
Enter fullscreen mode Exit fullscreen mode

frozen=True makes the dataclass add __setattr__ and __delattr__ methods that raise FrozenInstanceError, per the docs. So this fails, as you expect:

event.order_id = "o-2"  # raises FrozenInstanceError
Enter fullscreen mode Exit fullscreen mode

This does not fail:

event.metadata["retry"] = "1"  # mutates the event in place
Enter fullscreen mode Exit fullscreen mode

You never assigned to event.metadata. You called __setitem__ on the dict it holds, and the frozen dataclass has no say over that.

The hash failure has the same root. The docs say that when eq and frozen are both true, @dataclass generates a __hash__() for you. That generated hash combines the hashes of the fields. A dict field has no hash, so hash(event) raises TypeError and the event can't go in a set or be a dict key. The decorator does not warn you at class definition time, because default_factory=dict hides the dict from the check that rejects unhashable defaults.

A glass display case with a closed lid, but a drawer at the bottom slides open and papers spill out
frozen=True locks the lid. The dict inside is a drawer that still opens.

The 3.15 fix: a frozendict field

PEP 814 is Final and adds frozendict to builtins. The What's New entry sums it up: it "does not allow modification after creation", it "is not a subclass of dict; it inherits directly from object", and it "is hashable as long as all of its keys and values are hashable." It keeps insertion order, but comparison and hashing ignore order. The stdtypes docs list what it drops from the dict API: __setitem__, __delitem__, clear, pop, popitem, setdefault and update. |= does not modify it in place; it builds a new one.

The event, fixed:

from dataclasses import dataclass
from datetime import datetime

@dataclass(frozen=True)
class OrderPlaced:
    order_id: str
    placed_at: datetime
    metadata: frozendict[str, str] = frozendict()

    def __post_init__(self) -> None:
        if not isinstance(self.metadata, frozendict):
            frozen = frozendict(self.metadata)
            object.__setattr__(self, "metadata", frozen)
Enter fullscreen mode Exit fullscreen mode

The default is a plain frozendict(), no default_factory. Since 3.11 the decorator rejects defaults by hashability, not by type: "unhashable objects are now not allowed as default values", per the dataclasses docs. An empty frozendict is hashable, so it is accepted, and sharing one immutable instance across every event is safe.

The __post_init__ matters because annotations are not enforced at runtime: an inbound adapter that builds the event from a parsed request can still hand it a dict. The guard copies whatever mapping arrives into a frozendict. It uses object.__setattr__ because a normal assignment would hit the frozen __setattr__; the docs note the generated __init__ has to do the same thing.

The standard library made the same choice. In 3.15, dataclasses.field() with no metadata now uses "an empty frozendict, instead of a MappingProxyType() of an empty dict", according to the dataclasses changelog note.

pytest tests that prove it

Put these pytest tests next to the domain module. They need no database and no FastAPI app: the event is pure domain code, so its tests are plain function calls.

import dataclasses
from datetime import datetime, timezone

import pytest

from shop.domain.events import OrderPlaced

AT = datetime(2026, 11, 29, tzinfo=timezone.utc)

def make(**meta: str) -> OrderPlaced:
    return OrderPlaced("o-1", AT, frozendict(meta))

def test_fields_cannot_be_rebound():
    event = make(source="web")
    with pytest.raises(dataclasses.FrozenInstanceError):
        event.order_id = "o-2"  # type: ignore[misc]

def test_metadata_cannot_be_mutated():
    event = make(source="web")
    with pytest.raises(TypeError):
        event.metadata["source"] = "admin"  # type: ignore
Enter fullscreen mode Exit fullscreen mode

The next two cover the adapter edge and the outbox:

# same file: imports, AT and make() as above

def test_plain_dict_is_copied_and_frozen():
    raw = {"source": "web"}
    event = OrderPlaced("o-1", AT, raw)  # type: ignore
    raw["source"] = "admin"
    assert event.metadata["source"] == "web"
    assert type(event.metadata) is frozendict

def test_equal_events_hash_equal_and_dedupe():
    a = make(source="web", region="eu")
    b = make(region="eu", source="web")
    assert a == b
    assert hash(a) == hash(b)
    assert len({a, b}) == 1
Enter fullscreen mode Exit fullscreen mode

The last test is the one the outbox relay cares about. Two events built with the same metadata in a different key order are equal, hash the same, and collapse to one entry in a set. That relies on frozendict hashing being order-independent, which What's New shows directly: frozendict(x=1, y=2) and frozendict(y=2, x=1) compare equal and have equal hashes.

One more test, so nobody on the team over-trusts the type:

def test_frozendict_is_shallow():
    meta = frozendict(tags=["a"])
    meta["tags"].append("b")
    assert meta["tags"] == ["a", "b"]
    with pytest.raises(TypeError):
        hash(meta)
Enter fullscreen mode Exit fullscreen mode

frozendict freezes its own keys and values, not the objects those values point at. A list inside is still a list, and its presence makes the whole mapping unhashable. PEP 814 shows the same case: hash(frozendict(foo=['a', 'b', 'c'])) fails because a list is not hashable. For nested data, use tuples and nested frozendicts. If the data comes in as JSON, 3.15 also added an array_hook to json.loads(), and What's New says passing frozendict as object_pairs_hook and tuple as array_hook "will yield a deeply nested immutable Python structure."

Where the conversion lives in a hexagonal layout

The domain owns immutability. Adapters own formats. So the event keeps its frozendict, and the outbox adapter turns it back into plain JSON-friendly types at the edge:

import json

from shop.domain.events import OrderPlaced

def to_outbox_row(event: OrderPlaced) -> dict[str, str]:
    payload = {
        "order_id": event.order_id,
        "placed_at": event.placed_at.isoformat(),
        "metadata": dict(event.metadata),
    }
    return {
        "event_type": "OrderPlaced",
        "payload": json.dumps(payload),
    }
Enter fullscreen mode Exit fullscreen mode

dict(event.metadata) works because frozendict implements the Mapping protocol, per PEP 814. The adapter does not need to know whether the JSON encoder handles the new type; it hands the encoder a dict and moves on. The core stays standard library only, with no third-party immutable-map package for the domain to depend on.

A small framed window looking into a room where an unseen hand rearranges furniture
MappingProxyType is a window. Whoever holds the dict can still rearrange the room.

On 3.14: MappingProxyType, and what it doesn't give you

Before 3.15, the usual stand-in was types.MappingProxyType. Its docs describe it exactly: "Read-only proxy of a mapping. It provides a dynamic view on the mapping's entries, which means that when the mapping changes, the view reflects these changes." Read-only for you. Not for whoever still holds the dict.

from types import MappingProxyType

import pytest

def test_proxy_is_a_view_not_a_value():
    raw = {"source": "web"}
    view = MappingProxyType(raw)
    with pytest.raises(TypeError):
        view["source"] = "admin"  # type: ignore
    raw["source"] = "admin"
    assert view["source"] == "admin"
    with pytest.raises(TypeError):
        hash(view)
Enter fullscreen mode Exit fullscreen mode

The write through the proxy fails. The write to raw goes through and shows up in the view. And the hash fails too: since 3.12, hash(proxy) returns "a hash of the underlying mapping", and a dict has none. PEP 814 lists both gaps, saying the proxy "is not hashable", and that the underlying dict can still be reached and mutated, for example through gc.get_referents().

So a 3.14 version of the event has to copy the dict before wrapping it, and has to keep the field out of the hash:

from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import datetime
from types import MappingProxyType

@dataclass(frozen=True)
class OrderPlaced:
    order_id: str
    placed_at: datetime
    metadata: Mapping[str, str] = field(
        default_factory=lambda: MappingProxyType({}),
        hash=False,
    )

    def __post_init__(self) -> None:
        copy = MappingProxyType(dict(self.metadata))
        object.__setattr__(self, "metadata", copy)
Enter fullscreen mode Exit fullscreen mode

The copy cuts the link to the caller's dict, so the "someone else still holds it" problem goes away for normal code. hash=False makes the event hashable again by leaving metadata out of __hash__, while equality still compares it. That keeps equal events hashing equal, but the dataclasses docs say setting hash to anything other than None "is discouraged", and events that differ only in metadata now share a hash. == still tells them apart, so a set keeps both, but every lookup between them falls through to the equality check. It is a workaround. When your floor moves to 3.15, delete the hash=False, swap the type for frozendict, and the tests above tell you whether anything still depends on the old behavior.

The checklist for your value objects

Grep your domain package for frozen=True and look at every field type. dict, list and set inside a frozen dataclass are the places where "immutable" is only true at the top level. On 3.15, dict becomes frozendict, list becomes tuple, set becomes frozenset, and a __post_init__ guard converts whatever the adapters pass in. Then copy the test file from the pytest section next to each event module, so the next person who adds a dict field to an event gets a red test instead of a shared retry flag.


If this was useful

Value objects and domain events that stay put are the kind of core that Hexagonal Architecture in Python is built around: one async FastAPI + SQLAlchemy 2 service written five ways (Hexagonal, Clean, Onion, layered, vertical slice) and then measured, with the domain kept apart from the framework and the database behind clear ports. Every listing runs from the free companion repo, so you can try the patterns before you decide whether the book is for you.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (0)