Skip to content

Commit 0d55db8

Browse files
authored
perf: avoid deep copy (#702)
1 parent 6281fb2 commit 0d55db8

File tree

2 files changed

+9
-11
lines changed

2 files changed

+9
-11
lines changed

polyfactory/factories/base.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,10 @@ def _get_build_context(cls, build_context: BuildContext | None) -> BuildContext:
260260
if build_context is None:
261261
return {"seen_models": set()}
262262

263-
return copy.deepcopy(build_context)
263+
return {
264+
**build_context,
265+
"seen_models": copy.copy(build_context["seen_models"]),
266+
}
264267

265268
@classmethod
266269
def _infer_model_type(cls) -> type[T] | None:

polyfactory/factories/pydantic_factory.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from __future__ import annotations
22

3-
import copy
43
from contextlib import suppress
54
from datetime import timezone
65
from functools import partial
@@ -529,15 +528,11 @@ def _get_build_context(cls, build_context: BaseBuildContext | PydanticBuildConte
529528
:returns: PydanticBuildContext
530529
531530
"""
532-
if build_context is None:
533-
return {"seen_models": set(), "factory_use_construct": False}
531+
build_context = cast("PydanticBuildContext", super()._get_build_context(build_context))
532+
if build_context.get("factory_use_construct") is None:
533+
build_context["factory_use_construct"] = False
534534

535-
factory_use_construct = bool(build_context.get("factory_use_construct", False))
536-
537-
return {
538-
"seen_models": copy.deepcopy(build_context["seen_models"]),
539-
"factory_use_construct": factory_use_construct,
540-
}
535+
return build_context
541536

542537
@classmethod
543538
def _create_model(cls, _build_context: PydanticBuildContext, **kwargs: Any) -> T:
@@ -549,7 +544,7 @@ def _create_model(cls, _build_context: PydanticBuildContext, **kwargs: Any) -> T
549544
:returns: An instance of type T.
550545
551546
"""
552-
if cls._get_build_context(_build_context).get("factory_use_construct"):
547+
if _build_context.get("factory_use_construct"):
553548
if _is_pydantic_v1_model(cls.__model__):
554549
return cls.__model__.construct(**kwargs) # type: ignore[return-value]
555550
return cls.__model__.model_construct(**kwargs)

0 commit comments

Comments
 (0)