Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add simple validator metadata for use in annotated #316

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

tlambert03
Copy link
Member

@tlambert03 tlambert03 commented Jun 19, 2024

Playing around with a pattern to add simple validation via Annotated on evented dataclasses. There are no builtin validators. It simply allows someone to declare some simple validation prior to event emission. The use case would be when all you want is a way to cast fields without depending on a heavier library like pydantic.

from psygnal import evented, Validator

    def positive_int(value: Any) -> int:
        try:
            _value = int(value)
        except (ValueError, TypeError):
            raise ValueError("Value must be an integer") from None
        if not _value > 0:
            raise ValueError("Value must be positive")
        return _value

    @evented
    @dataclass
    class Foo:
        x: Annotated[int, Validator(positive_int)]

(btw, @d-v-b, this is a general pattern that might work for you in zarr. The trick for you would just be determining when where to patch the __setattr__ method of the parent class)

Copy link

codspeed-hq bot commented Jun 19, 2024

CodSpeed Performance Report

Merging #316 will not alter performance

Comparing tlambert03:validators (5010f17) with main (18a6ec2)

Summary

✅ 66 untouched benchmarks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants