polyfactory icon indicating copy to clipboard operation
polyfactory copied to clipboard

fix: Adjust min/max items to valid lengths for Set[Enum] fields

Open adrianeboyd opened this issue 1 year ago • 6 comments

Description

For Set[Enum] fields with a limited maximum length, adjust min_items and max_items to be within the range of valid lengths.

Closes

Fixes #565

adrianeboyd avatar Jul 19 '24 11:07 adrianeboyd

The question from #565 about whether this should raise an error instead or warn in addition remains open.

adrianeboyd avatar Jul 19 '24 11:07 adrianeboyd

I am not really sure whether this is sufficient for handling all possible ways of defining fields with enums? Or whether isinstance(..., EnumMeta) is the best way to check?

adrianeboyd avatar Jul 19 '24 12:07 adrianeboyd

What if we just don't handle this? Instead, we could just raise an exception telling the user the minimum is too large. It might be due to the default set by polyfactory, but this way we can tell the user to change it themselves. I don't really like the idea of us just changing a value without them knowing. I don't think it would be a breaking change either since it currently results in an infinite loop anyway.

vkcku avatar Jul 20 '24 04:07 vkcku

Thanks for the review! I think I addressed all the individual suggestions, although handling Literal seemed clunkier than I expected, so maybe there's a better way to do that?

In terms of raising an error or not, I'm not particularly familiar with polyfactory so it might just be my understanding, but it seems difficult to configure the min/max length on a per-item basis. How would you (easily) set the intended lengths for a model like this?

class WithSetEnum(BaseModel):
    letters: Set[Enum("Letters", ["a", "b", "c", "d", "e", "f"])]
    colors: Set[Enum("Colors", ["red", "green"])]

adrianeboyd avatar Jul 20 '24 09:07 adrianeboyd

Thanks for the review! I think I addressed all the individual suggestions, although handling Literal seemed clunkier than I expected, so maybe there's a better way to do that?

In terms of raising an error or not, I'm not particularly familiar with polyfactory so it might just be my understanding, but it seems difficult to configure the min/max length on a per-item basis. How would you (easily) set the intended lengths for a model like this?

class WithSetEnum(BaseModel):
    letters: Set[Enum("Letters", ["a", "b", "c", "d", "e", "f"])]
    colors: Set[Enum("Colors", ["red", "green"])]

Yeah this is a bit tricky since you'd have to set the min val as 0 and max val as 2. I'm not sure what the best way to go about this would be. You could also have a classmethod for generating the values for that specific field and manually call handle_constrained_collection.

vkcku avatar Jul 23 '24 03:07 vkcku

Documentation preview will be available shortly at https://litestar-org.github.io/polyfactory-docs-preview/567

github-actions[bot] avatar Aug 26 '24 06:08 github-actions[bot]