Skip to content

Validator counting occurrences #1508

@AdrianSosic

Description

@AdrianSosic

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 validator

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions