Backtestspydanticrun-20261022-024030#13867

Issue #13867 Merged fix PR #13871 Run 22 Oct 2026 · run-20261022-024030 pydantic/pydantic

FieldInfo.get_default is 5-6x slower on 2.13 because of a relative import in the function body

Better

Our patch was judged better than the merged fix.

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

The source changes in both patches are byte-identical: both hoist `smart_deepcopy` into the existing module-level `from ._utils import ...` line and delete the per-call relative import from `resolve_default_value`. This addresses the root cause named in the issue (the `resolve_name` cost paid on every call of the relative in-body import), and the independent tests confirm both patches move all six base failures to PASS. So correctness and scope are a wash. The difference is tests: Patch A adds none, so nothing would catch a regression if someone reintroduced a lazy import on this hot path. Patch B adds regression tests that record calls to `builtins.__import__` during `get_default()`, `model_construct()`, and private-attribute default resolution, asserting none occur. These would fail on the base commit (the independent harness used the same technique and saw `_utils` imports recorded on base) and pass after the fix, so they are non-tautological and cover the exact scenarios the issue describes, including the `model_construct` case and both `default`/`default_factory` branches. The tests warm up before recording and restore `__import__` via `monkeypatch.undo()`, which is careful enough. Monkeypatching `__import__` is slightly unusual but is the only direct way to assert the absence of an import statement, and it is scoped to the call under test. Patch B is the better fix because it delivers the same correct change plus meaningful protection against recurrence.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

3m 29s

Wall-clock time in the container

Full test suite

No new failures

117 passed · 2 skipped · 119 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

67vs 4 merged

Changed lines, ours vs merged

FieldInfo.get_default() costs about five to six times more on 2.13 than on 2.12.

On 2.13 the call is delegated to pydantic._internal._fields.resolve_default_value, whose body starts with a relative import that runs on every call:

def resolve_default_value(...):
    from ._utils import smart_deepcopy

On 2.12 the plain-default branch was return _utils.smart_deepcopy(self.default), with no import at call time. In 2.13 the import sits before the default_factory branch, so every call pays it.

_fields.py already has a module-level import from ._utils, so the in-body import is not breaking an import cycle, and moving the name up adds nothing to import time.

Measured with timeit, best of 5 runs of 200000 calls:

2.12.32.13.52.13.5, import moved up
FieldInfo(default=123)55 ns300 ns85 ns
FieldInfo(default_factory=list)35 ns271 ns60 ns

The cost is the import statement rather than module loading, since the module is already in sys.modules. With the relative form, resolve_name runs before the sys.modules lookup, so it is paid on every call even though the module is cached. A three-function package, identical except for the import form used to obtain the same callee:

formper call
from ._helper import work inside the body234 ns
from pkg._helper import work inside the body108 ns
module-level import32 ns

Moving the import up removes most of the gap but not all of it. What is left is the extra resolve_default_value call and the sentinel checks added to smart_deepcopy.

This is visible in model_construct(), where get_default runs once per field. For a five-field model with defaults: 1.18 us on 2.12.3 against 2.49 us on 2.13.5. Passing every field explicitly, so that no default is resolved, gives 1.12 us on both.

Version info

pydantic 2.13.5, CPython 3.13, macOS on arm64. The in-body import is still on main. Not measured on Linux or x86_64, so the absolute numbers will differ there, though the ratios should hold.

The two patches

Our patch+64 −3
pydantic/_internal/_fields.pyindex 29cde2df..51e7c9f0 100644@@ -25,7 +25,7 @@ from ._docs_extraction import extract_docstrings_from_cls from ._import_utils import import_cached_base_model, import_cached_field_info from ._namespace_utils import NsResolver from ._repr import Representation-from ._utils import can_be_positional, get_first_not_none+from ._utils import can_be_positional, get_first_not_none, smart_deepcopy  if TYPE_CHECKING:     from annotated_types import BaseMetadata@@ -866,8 +866,6 @@ def resolve_default_value(     call_default_factory: bool = False, ) -> Any:     """Resolve the default value using either a static default or a default_factory."""-    from ._utils import smart_deepcopy-     if default_factory is None:         return smart_deepcopy(default)     if call_default_factory:tests/test_fields.pyindex 5c8dc1ae..301c6cb2 100644@@ -1,3 +1,4 @@+import builtins import copy from typing import Annotated, Any, Final, Generic, TypeVar @@ -473,3 +474,65 @@ def test_default_factory_without_validated_data_unsupported() -> None: ) def test_privateattr_repr(private_attr: ModelPrivateAttr, result: str) -> None:     assert repr(private_attr) == result+++def _record_imports(monkeypatch: pytest.MonkeyPatch) -> list[str]:+    imports: list[str] = []+    original_import = builtins.__import__++    def recording_import(name, *args, **kwargs):+        imports.append(name)+        return original_import(name, *args, **kwargs)++    monkeypatch.setattr(builtins, '__import__', recording_import)+    return imports+++@pytest.mark.parametrize(+    'field_info',+    [FieldInfo(default=123), FieldInfo(default=[1, 2]), FieldInfo(default_factory=list)],+    ids=['immutable_default', 'mutable_default', 'default_factory'],+)+def test_get_default_does_not_import_at_call_time(field_info: FieldInfo, monkeypatch: pytest.MonkeyPatch) -> None:+    """`get_default()` is on hot paths (e.g. `model_construct()`), so it must not run import statements per call."""+    expected = field_info.get_default(call_default_factory=True)++    imports = _record_imports(monkeypatch)+    result = field_info.get_default(call_default_factory=True)+    field_info.get_default()+    monkeypatch.undo()++    assert result == expected+    assert imports == []+++def test_model_construct_defaults_do_not_import_at_call_time(monkeypatch: pytest.MonkeyPatch) -> None:+    class Model(BaseModel):+        a: int = 1+        b: list[int] = [1]+        c: dict[str, int] = Field(default_factory=dict)++    Model.model_construct()  # warm up++    imports = _record_imports(monkeypatch)+    m = Model.model_construct()+    monkeypatch.undo()++    assert m.model_dump() == {'a': 1, 'b': [1], 'c': {}}+    assert imports == []+++def test_private_attr_defaults_do_not_import_at_call_time(monkeypatch: pytest.MonkeyPatch) -> None:+    class Model(BaseModel):+        _a: int = 1+        _b: list[int] = PrivateAttr(default=[1])+        _c: dict[str, int] = PrivateAttr(default_factory=dict)++    Model()  # warm up++    imports = _record_imports(monkeypatch)+    m = Model()+    monkeypatch.undo()++    assert (m._a, m._b, m._c) == (1, [1], {})+    assert imports == [] 
Merged fix · PR #13871+1 −3
pydantic/_internal/_fields.pyindex 29cde2dff..51e7c9f01 100644@@ -25,7 +25,7 @@ from ._docs_extraction import extract_docstrings_from_cls from ._import_utils import import_cached_base_model, import_cached_field_info from ._namespace_utils import NsResolver from ._repr import Representation-from ._utils import can_be_positional, get_first_not_none+from ._utils import can_be_positional, get_first_not_none, smart_deepcopy  if TYPE_CHECKING:     from annotated_types import BaseMetadata@@ -866,8 +866,6 @@ def resolve_default_value(     call_default_factory: bool = False, ) -> Any:     """Resolve the default value using either a static default or a default_factory."""-    from ._utils import smart_deepcopy-     if default_factory is None:         return smart_deepcopy(default)     if call_default_factory: