psygnal icon indicating copy to clipboard operation
psygnal copied to clipboard

feat: Add simple validator metadata for use in annotated

Open tlambert03 opened this issue 1 year ago • 1 comments

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)

tlambert03 avatar Jun 19 '24 22:06 tlambert03

CodSpeed Performance Report

Merging #316 will not alter performance

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

Summary

✅ 66 untouched benchmarks

codspeed-hq[bot] avatar Jun 19 '24 22:06 codspeed-hq[bot]

changed my mind on this feature. scope creepy

tlambert03 avatar Jun 21 '25 22:06 tlambert03