Pydantic: generate unique lists #664
-
Since Pydantic v2, unique lists are no longer natively supported ( Therefore, I resorted to using a custom validator (inspired by pydantic/pydantic-core#296 (comment) and pydantic/pydantic-core#820 (comment)): UniqueListItem = TypeVar("UniqueListItem", bound=Hashable)
def validate_unique_list(value: list[UniqueListItem]) -> list[UniqueListItem]:
"""Validate that list contains only unique items.
Taken from https://github.com/pydantic/pydantic-core/pull/820#issuecomment-1670475909
"""
if len(value) == len(set(value)):
return value
raise PydanticCustomError("unique_list", "List must be unique")
PydanticTypeUniqueList = Annotated[
List[UniqueListItem],
AfterValidator(validate_unique_list),
Field(json_schema_extra={"uniqueItems": True}),
] Because Polyfactory doesn't know about Normally, I would just add So, I think I need a way to call Polyfactory's value generation for list items, inside a custom wrapper that prevents duplicates. Can anyone point me to the primitives that I can use (assuming they are public APIs, and invokable outside the build context)? I read through |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Hi @WilliamDEdwards ! I think the would need to Some alternative approaches would be
PydanticTypeUniqueList = Annotated[
List[UniqueListItem],
AfterValidator(validate_unique_list),
Field(json_schema_extra={"uniqueItems": True}),
{'unique_items': True}
] This adds some duplication but uses existing tested constraint parsing so that this is applied for polyfactory.
class MyFactory(ModelFactory[A]):
@classmethod
def process_kwargs(self, *args, **kwargs) -> dict:
kwargs = super().process_kwargs()
kwargs['my_field'] = list(set(kwargs['my_field'])
return kwargs Exact typing and usage may need to be adjusted especially if other constraints on field |
Beta Was this translation helpful? Give feedback.
Hi @WilliamDEdwards !
I think the would need to
UniqueListItem
should be bound at this point so would need to overridePydanticTypeUniqueList
so the constraint could be applied at that level. Some of the logic is quite deep in functions so not super easy to override this waySome alternative approaches would be
This adds some duplication but uses existing tested constraint parsing so that this is applied for polyfactory.
process_kwargs
(and cov…