Skip to content

Commit e9daae0

Browse files
committed
fixup! feat: add a factory supporting pydantic dataclasses
1 parent 24efcbf commit e9daae0

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

polyfactory/factories/pydantic_factory.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import copy
44
from contextlib import suppress
5+
from dataclasses import is_dataclass
56
from datetime import timezone
67
from functools import partial
78
from os.path import realpath
@@ -55,7 +56,6 @@
5556
ModelField, # pyright: ignore[attr-defined,reportAttributeAccessIssue]
5657
Undefined, # pyright: ignore[attr-defined,reportAttributeAccessIssue]
5758
)
58-
from pydantic.dataclasses import is_pydantic_dataclass
5959

6060
# Keep this import last to prevent warnings from pydantic if pydantic v2
6161
# is installed.
@@ -69,7 +69,6 @@
6969

7070
# v2 specific imports
7171
from pydantic import BaseModel as BaseModelV2
72-
from pydantic.dataclasses import is_pydantic_dataclass
7372
from pydantic_core import PydanticUndefined as UndefinedV2
7473
from pydantic_core import to_json
7574

@@ -101,6 +100,8 @@
101100

102101
from typing_extensions import NotRequired, TypeGuard
103102

103+
from pydantic.dataclasses import PydanticDataclass # pyright: ignore[reportPrivateImportUsage]
104+
104105
ModelT = TypeVar("ModelT", bound="BaseModelV1 | BaseModelV2") # pyright: ignore[reportInvalidTypeForm]
105106
T = TypeVar("T")
106107

@@ -626,6 +627,11 @@ def _is_pydantic_v2_model(model: Any) -> TypeGuard[BaseModelV2]: # pyright: ign
626627
return not _IS_PYDANTIC_V1 and is_safe_subclass(model, BaseModelV2)
627628

628629

630+
def is_pydantic_dataclass(cls: type[Any]) -> TypeGuard[PydanticDataclass]:
631+
# This method is available in the `pydantic.dataclasses` module for python >= 3.9
632+
return is_dataclass(cls) and "__pydantic_validator__" in cls.__dict__
633+
634+
629635
class PydanticDataclassFactory(ModelFactory[T]): # type: ignore[type-var]
630636
"""Base factory for pydantic dataclasses"""
631637

0 commit comments

Comments
 (0)