-
-
Notifications
You must be signed in to change notification settings - Fork 411
Open
Description
Hi @hynek, just wanted to quickly hear your thoughts on this:
I've several times encountered the situation that I need to check if a collection-valued attribute contains a certain reference element exactly once and wrote a custom validator for this. Because this is a rather generic condition not related to any particular use case or business logic, I was wondering if it makes sense to add the functionality to the attrs core library. One could make it even more flexible to ensure the count is between some min and max range.
Let me know what you think, I'd be happy to push a PR if you like it but I'm also fine if you say it's not relevant enough.
The current logic with fixed element count is:
def validate_contains_exactly_one(
value: Any, /
) -> Callable[[Parameter, Attribute, Collection[Any]], None]:
"""Make a validator to check an attribute contains a certain value exactly once."""
def validator( # noqa: DOC101, DOC103
obj: Parameter, attribute: Attribute, values: Collection[Any]
) -> None:
"""Validate that the input contains a reference element exactly once.
Raises:
ValueError: If the input does not contain the reference exactly once.
"""
if (count := list(values).count(value)) != 1:
raise ValueError(
f"The '{attribute.alias}' attribute of parameter '{obj.name}' must "
f"contain the element '{value}' exactly once. "
f"Found {count} such elements in the given input: {values}."
)
return validatorReactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels