Backtestspydanticrun-20261013-104308#13617

Issue #13617 Merged fix PR #13623 Run 13 Oct 2026 · run-20261013-104308 pydantic/pydantic

Cannot create defauldict field with dict value type

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches fix the root cause by adding `dict` (and `frozenset`) to the inferred default-factory mapping, so `defaultdict[str, dict]` works. Patch B does exactly that, minimally, inside the existing dict. Its tests would fail before the fix and pass after: they cover `dict`, `dict[str, int]`, `typing.Dict[str, int]`, `frozenset` and `frozenset[int]`, and check both the value and the exact type. It also adds a BaseModel test that reproduces the issue's example (`prop: defaultdict[str, dict] = defaultdict(dict)`). Patch A fixes the issue too, and it corrects the 'keys' → 'values' wording in the error message. But it adds a Python-3.15-only branch that silently remaps `collections.abc.Mapping` from `dict` to `frozendict`. That is an unrelated behavior change: on newer Pythons, existing users of `defaultdict[..., Mapping]` would get immutable defaults, which risks breaking code that mutates them. It also relies on an undeclared `frozendict` name with `noqa: F821`. Patch A rewrites the existing infer test into a parametrized version, which gives reasonable coverage, but it does not test parameterized `dict[...]` or the model scenario from the issue. On the narrow fix the two are equivalent. B wins because it avoids A's risky scope creep and its tests target the reported scenario more directly.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

2m 46s

Wall-clock time in the container

Full test suite

No new failures

386 passed · 4 skipped · 390 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

31vs 89 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

For now it's impossible to create a model with defaultdict(dict) value.
It's possible to create with Mapping and MutableMapping types, then why not add the basic simple type dict? Other basic types are allowed too.

The corresponding code is located here.

Example Code

from collections import defaultdict
from pydantic import BaseModel

class Test(BaseModel):
    prop: defaultdict[str, dict] = defaultdict(dict)
# ...
# pydantic.errors.PydanticSchemaGenerationError: Unable to infer a default factory for keys of type <class 'dict'>. Only float, frozenset, int, dict, str, set, list, tuple, bool are supported, other types require an explicit default factory set using `DefaultDict[..., Annotated[..., Field(default_factory=...)]]`

Python, Pydantic & OS Version

             pydantic version: 2.13.4
        pydantic-core version: 2.46.4
          pydantic-core build: profile=release pgo=false
               python version: 3.11.9 (tags/v3.11.9:de54cf5, Apr  2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)]
                     platform: Windows-10-10.0.26200-SP0
             related packages: fastapi-0.116.0 pydantic-settings-2.9.1 typing_extensions-4.15.0
                       commit: unknown

The two patches

Our patch+31 −0
pydantic/_internal/_validators.pyindex 729c5fae..b6482665 100644@@ -427,8 +427,10 @@ def get_defaultdict_default_default_factory(values_source_type: Any) -> Callable             collections.abc.MutableSequence: list,             list: list,             set: set,+            frozenset: frozenset,             collections.abc.MutableSet: set,             collections.abc.Set: frozenset,+            dict: dict,             collections.abc.Mapping: dict,             collections.abc.MutableMapping: dict,             float: float,tests/types/test_defaultdict.pyindex 67131324..db08c6f9 100644@@ -1,3 +1,4 @@+import typing from collections import defaultdict from typing import Annotated, Any, TypeVar @@ -6,6 +7,7 @@ from pydantic_core import CoreSchema, core_schema from typing_extensions import get_args  # noqa: UP035 (for `get_args`)  from pydantic import (+    BaseModel,     Field,     GetCoreSchemaHandler,     PydanticSchemaGenerationError,@@ -51,6 +53,33 @@ def test_defaultdict_infer_default_factory() -> None:     assert v.default_factory() == set()  +@pytest.mark.parametrize(+    'value_type,expected',+    [+        (dict, {}),+        (dict[str, int], {}),+        (typing.Dict[str, int], {}),  # noqa: UP006+        (frozenset, frozenset()),+        (frozenset[int], frozenset()),+    ],+)+def test_defaultdict_infer_default_factory_builtin_containers(value_type: Any, expected: Any) -> None:+    v = TypeAdapter(defaultdict[str, value_type]).validate_python({})+    assert v.default_factory is not None+    assert v['missing'] == expected+    assert type(v['missing']) is type(expected)+++def test_defaultdict_dict_values_in_model() -> None:+    class Model(BaseModel):+        prop: defaultdict[str, dict] = defaultdict(dict)++    m = Model(prop={'a': {'x': 1}})+    assert m.prop['a'] == {'x': 1}+    assert m.prop['b'] == {}+    assert Model().prop['c'] == {}++ def test_defaultdict_explicit_default_factory() -> None:     class MyList(list[int]):         pass 
Merged fix · PR #13623+54 −35
pydantic/_internal/_validators.pyindex 729c5fae4..9ce71efe7 100644@@ -8,6 +8,7 @@ from __future__ import annotations as _annotations import collections.abc import math import re+import sys import typing from collections.abc import Callable, Sequence from decimal import Decimal@@ -415,27 +416,35 @@ def defaultdict_validator(         return collections.defaultdict(default_default_factory, handler(input_value))  +_defaultdict_allowed_default_types: dict[type[Any], type[Any]] = {+    float: float,+    int: int,+    str: str,+    bool: bool,+    tuple: tuple,+    collections.abc.Sequence: tuple,+    collections.abc.MutableSequence: list,+    list: list,+    set: set,+    collections.abc.MutableSet: set,+    frozenset: frozenset,+    collections.abc.Set: frozenset,+    dict: dict,+    collections.abc.Mapping: dict,+    collections.abc.MutableMapping: dict,+}++if sys.version_info >= (3, 15):+    _defaultdict_allowed_default_types[collections.abc.Mapping] = frozendict  # noqa: F821+    _defaultdict_allowed_default_types[frozendict] = frozendict  # noqa: F821++ def get_defaultdict_default_default_factory(values_source_type: Any) -> Callable[[], Any]:     FieldInfo = import_cached_field_info()      values_type_origin = get_origin(values_source_type)      def infer_default() -> Callable[[], Any]:-        allowed_default_types: dict[Any, Any] = {-            tuple: tuple,-            collections.abc.Sequence: tuple,-            collections.abc.MutableSequence: list,-            list: list,-            set: set,-            collections.abc.MutableSet: set,-            collections.abc.Set: frozenset,-            collections.abc.Mapping: dict,-            collections.abc.MutableMapping: dict,-            float: float,-            int: int,-            str: str,-            bool: bool,-        }         values_type = values_type_origin or values_source_type         instructions = 'set using `DefaultDict[..., Annotated[..., Field(default_factory=...)]]`'         if typing_objects.is_typevar(values_type):@@ -447,15 +456,15 @@ def get_defaultdict_default_default_factory(values_source_type: Any) -> Callable                 )              return type_var_default_factory-        elif values_type not in allowed_default_types:+        elif values_type not in _defaultdict_allowed_default_types:             # a somewhat subjective set of types that have reasonable default values-            allowed_msg = ', '.join([t.__name__ for t in set(allowed_default_types.keys())])+            allowed_msg = ', '.join([t.__name__ for t in _defaultdict_allowed_default_types.keys()])             raise PydanticSchemaGenerationError(-                f'Unable to infer a default factory for keys of type {values_source_type}.'+                f'Unable to infer a default factory for values of type {values_source_type}.'                 f' Only {allowed_msg} are supported, other types require an explicit default factory'                 ' ' + instructions             )-        return allowed_default_types[values_type]+        return _defaultdict_allowed_default_types[values_type]      # Assume Annotated[..., Field(...)]     if typing_objects.is_annotated(values_type_origin):tests/types/test_defaultdict.pyindex 671313244..b688da7f4 100644@@ -1,3 +1,4 @@+import sys from collections import defaultdict from typing import Annotated, Any, TypeVar @@ -24,31 +25,40 @@ def test_typing_coercion_defaultdict():   def test_defaultdict_unknown_default_factory() -> None:-    """-    https://github.com/pydantic/pydantic/issues/4687-    """+    """https://github.com/pydantic/pydantic/issues/4687"""     with pytest.raises(         PydanticSchemaGenerationError,-        match=r'Unable to infer a default factory for keys of type collections.defaultdict\[int, int\]',+        match=r'Unable to infer a default factory for values of type collections.defaultdict\[int, int\]',     ):         TypeAdapter(defaultdict[int, defaultdict[int, int]])  -def test_defaultdict_infer_default_factory() -> None:-    ta_list = TypeAdapter(defaultdict[int, list[int]])-    v = ta_list.validate_python({})-    assert v.default_factory is not None-    assert v.default_factory() == []+defaultdict_types_params = [+    (int, 0),+    (float, 0.0),+    (str, ''),+    (bool, False),+    (tuple, ()),+    (list[int], []),+    (list, []),+    (set, set()),+    (frozenset, frozenset()),+    (dict, {}),+] -    ta_int = TypeAdapter(defaultdict[int, int])-    v = ta_int.validate_python({})-    assert v.default_factory is not None-    assert v.default_factory() == 0+if sys.version_info >= (3, 15):+    defaultdict_types_params.append((frozendict, frozendict()))  # noqa: F821 -    ta_set = TypeAdapter(defaultdict[int, set])-    v = ta_set.validate_python({})++@pytest.mark.parametrize(+    ['default_factory_type', 'value'],+    defaultdict_types_params,+)+def test_defaultdict_infer_default_factory(default_factory_type: Any, value: Any) -> None:+    ta_list = TypeAdapter(defaultdict[int, default_factory_type])+    v = ta_list.validate_python({})     assert v.default_factory is not None-    assert v.default_factory() == set()+    assert v.default_factory() == value   def test_defaultdict_explicit_default_factory() -> None: