pyapp-kit / psygnal

Python observer pattern (callback/event system). Modeled after Qt Signals & Slots (but independent of Qt)
https://psygnal.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
84 stars 13 forks source link

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

Open tlambert03 opened 4 months ago

tlambert03 commented 4 months ago

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)

codspeed-hq[bot] commented 4 months ago

CodSpeed Performance Report

Merging #316 will not alter performance

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

Summary

✅ 66 untouched benchmarks