Backtestspydanticrun-20261007-130130#13867
FieldInfo.get_default is 5-6x slower on 2.13 because of a relative import in the function body
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
The source changes are byte-for-byte identical. Both move `smart_deepcopy` into the existing module-level `from ._utils import ...` line in `_fields.py` and delete the in-body relative import from `resolve_default_value`. That removes the root cause the issue identifies (the per-call `resolve_name`/import-statement overhead), so correctness, scope and craft of the fix are equal. The difference is tests. Patch B adds none. Patch A adds a regression test that monkeypatches `builtins.__import__` to raise while calling `get_default()`. It covers plain defaults, mutable defaults, `default_factory`, factories that take validated data, and `PrivateAttr` variants, and adds a `model_construct()` case. Before the fix, the `from ._utils import smart_deepcopy` statement goes through `__import__` and the test fails. After the fix it passes. So the test directly encodes the regression rather than being tautological. The tests are somewhat brittle, since any future lazy import anywhere on these paths would trip them. But that is arguably the intended guard for a hot path, and it adds no risk to library code. With identical fixes, Patch A's meaningful regression coverage makes it the better patch.
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
6m 47s
Wall-clock time in the container
Full test suite
No new failures
12,874 passed · 526 skipped · 13,400 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
66vs 4 merged
Changed lines, ours vs merged
The issue
View on GitHubFieldInfo.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.3 | 2.13.5 | 2.13.5, import moved up | |
|---|---|---|---|
FieldInfo(default=123) | 55 ns | 300 ns | 85 ns |
FieldInfo(default_factory=list) | 35 ns | 271 ns | 60 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:
| form | per call |
|---|---|
from ._helper import work inside the body | 234 ns |
from pkg._helper import work inside the body | 108 ns |
| module-level import | 32 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
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..777cb9d9 100644@@ -1,4 +1,7 @@+import builtins import copy+from collections.abc import Iterator+from contextlib import contextmanager from typing import Annotated, Any, Final, Generic, TypeVar import pytest@@ -463,6 +466,65 @@ def test_default_factory_without_validated_data_unsupported() -> None: FooBar.model_fields['a'].get_default(call_default_factory=True) +@contextmanager+def _forbid_imports() -> Iterator[None]:+ """Make any `import` statement executed within the context raise."""++ def _import(name: str, *args: Any, **kwargs: Any) -> Any:+ raise AssertionError(f'Unexpected import at call time: {name!r}')++ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(builtins, '__import__', _import)+ yield+++@pytest.mark.parametrize(+ 'field_info',+ [+ pytest.param(FieldInfo(default=123), id='default'),+ pytest.param(FieldInfo(default=[1, 2]), id='mutable_default'),+ pytest.param(FieldInfo(default_factory=list), id='default_factory'),+ pytest.param(FieldInfo(default_factory=lambda data: data['a']), id='default_factory_with_data'),+ pytest.param(PrivateAttr(default=123), id='private_attr_default'),+ pytest.param(PrivateAttr(default_factory=list), id='private_attr_default_factory'),+ ],+)+def test_get_default_does_not_import_at_call_time(field_info: Any) -> None:+ """https://github.com/pydantic/pydantic/issues/13867++ Resolving a default is on hot paths (e.g. `model_construct()`), it must not execute import statements.+ """+ expected_default = field_info.get_default()+ if field_info.default_factory is None:+ expected_called = expected_default+ elif getattr(field_info, 'default_factory_takes_validated_data', False):+ expected_called = 1+ else:+ expected_called = []++ with _forbid_imports():+ default = field_info.get_default()+ called = field_info.get_default(call_default_factory=True, validated_data={'a': 1})++ assert default == expected_default+ assert called == expected_called+++def test_model_construct_defaults_do_not_import_at_call_time() -> None:+ """https://github.com/pydantic/pydantic/issues/13867"""++ class Model(BaseModel):+ a: int = 1+ b: list[int] = [1]+ c: list[int] = Field(default_factory=list)+ d: int = Field(default_factory=lambda data: data['a'] + 1)++ with _forbid_imports():+ m = Model.model_construct()++ assert m.model_dump() == {'a': 1, 'b': [1], 'c': [], 'd': 2}++ @pytest.mark.parametrize( ['private_attr', 'result'], [
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: