Repository navigation
Description
- cattrs version: 26.2.1, and
mainat e9239b7 - Python version: 3.13.16 (pymongo 4.19.0)
- Operating System: Linux (python:3.13-slim container)
Description
With the bson preconf converter, structuring into a TypedDict returns the input dict as it is. The field hooks never run, so a date stays the ISO string that the converter itself wrote, a nested attrs class stays a dict, and wrong types or missing required keys raise nothing. The json converter handles the same TypedDict correctly. Counter[str] is affected the same way and comes back as a plain dict with unconverted values.
As far as I can tell, cattrs.preconf.bson.configure_converter registers its is_mapping structure hook factory after Converter.__init__ has registered the TypedDict, Counter and defaultdict factories. TypedDicts are dict subclasses, so the bson mapping factory takes precedence. Calling c.register_structure_hook_factory(is_typeddict, c.gen_structure_typeddict) on a bson converter, with is_typeddict from cattrs._compat, makes a TypedDict like Event below structure correctly.
What I Did
from collections import Counter
from datetime import date
from typing import TypedDict
import attrs
from cattrs.preconf.bson import make_converter as bson_converter
from cattrs.preconf.json import make_converter as json_converter
@attrs.define
class User:
name: str
class Event(TypedDict):
day: date
count: int
owner: User
doc = {"day": date(2026, 11, 10), "count": 3, "owner": User("ann")}
for make in (json_converter, bson_converter):
c = make()
name = make.__module__.rsplit(".", 1)[-1]
print(name, c.loads(c.dumps(doc, unstructure_as=Event), Event))
for bad in ({"count": 3}, {"day": "x", "count": "three", "owner": 1}):
try:
print(name, c.structure(bad, Event))
except Exception as e:
print(name, type(e).__name__, e)
print(name, repr(c.structure({"a": "2"}, Counter[str])))json {'day': datetime.date(2026, 11, 10), 'count': 3, 'owner': User(name='ann')}
json ClassValidationError While structuring Event (2 sub-exceptions)
json ClassValidationError While structuring Event (3 sub-exceptions)
json Counter({'a': 2})
bson {'day': '2026-11-10', 'count': 3, 'owner': {'name': 'ann'}}
bson {'count': 3}
bson {'day': 'x', 'count': 'three', 'owner': 1}
bson {'a': '2'}
The output is the same on 26.2.1 and on main.
Expected: the bson converter structures Event the way the json converter does, and returns a Counter for Counter[str].
Activity