Replies: 3 comments 5 replies
-
You'll have to use from pydantic.dataclasses import Field, dataclass
from polyfactory.factories.dataclass_factory import DataclassFactory
@dataclass
class Foo:
foo: int = Field(gt=10000)
class FooFactory(DataclassFactory[Foo]):
__model__ = Foo
foo = FooFactory.build() |
Beta Was this translation helpful? Give feedback.
-
that should keep you entertained :) https://jcristharif.com/msgspec/benchmarks.html#benchmarks |
Beta Was this translation helpful? Give feedback.
-
This discussion is fairly old. However, in case someone decides to use pydantic dataclasses with """Extensions for the `polyfactory` library."""
from __future__ import annotations
from dataclasses import is_dataclass
from typing import TYPE_CHECKING
from typing import Any
from typing import TypeGuard
from polyfactory.factories.base import T
from polyfactory.factories.pydantic_factory import ModelFactory
from polyfactory.factories.pydantic_factory import PydanticFieldMeta
from polyfactory.field_meta import FieldMeta
if TYPE_CHECKING:
from pydantic.dataclasses import PydanticDataclass
def _is_pydantic_dataclass(value: Any) -> TypeGuard[PydanticDataclass]:
return bool(is_dataclass(value) and hasattr(value, "__pydantic_config__"))
class PydanticDataclassFactory(ModelFactory[T]):
"""Abstract factory building on top of Pydantic Model factory factory to
provide support for pydantic dataclasses *including constraints*.
"""
# Open discussion on this topic:
# https://github.com/litestar-org/polyfactory/discussions/393
__is_base_factory__ = True
@classmethod
def is_supported_type(cls, value: Any) -> TypeGuard[type[T]]:
return _is_pydantic_dataclass(value)
@classmethod
def get_model_fields(cls) -> list[FieldMeta]:
assert _is_pydantic_dataclass(cls.__model__)
pydantic_fields = cls.__model__.__pydantic_fields__
pydantic_config = cls.__model__.__pydantic_config__
cls._fields_metadata = [
PydanticFieldMeta.from_field_info(
field_info=field_info,
field_name=field_name,
random=cls.__random__,
use_alias=not pydantic_config.get(
"populate_by_name",
False,
),
)
for field_name, field_info in pydantic_fields.items()
]
return cls._fields_metadata |
Beta Was this translation helpful? Give feedback.
-
Modern versions of Pydantic support adding validation on top of native Python dataclasses. If we're looking to use Polyfactory for testing in a codebase featuring these Pydantic data classes, what's the most appropriate Polyfactory factory type?
Should we be using the
DataclassFactory
or theModelFactory
?Beta Was this translation helpful? Give feedback.
All reactions