attrs
attrs copied to clipboard
Support for a validator argument to enable runtime validation
A while ago I created https://github.com/bloomberg/attrs-strict a library to help with runtime validation of attrs classes.
The way it currently works is you need to "enable" it per attribute in the following manner:
attr.ib(validator=type_validator(), type=List[Tuple[str, str]])
But if you have multiple fields, and you want to apply the validation on all of them, it becomes repetitive. Additionally, you might miss adding it for some attributes.
Would you consider an argument that could enable it for all the existing attributes in an attrs class ? Something along the lines:
attr.s(validate_with=type_validator())
class Something:
...
Shouldn't that be possible with field_transformer? See https://www.attrs.org/en/stable/extending.html#automatic-field-transformation-and-modification
I think it would work if you write an extension and call it on every field so instead of the example above, you'd need something like:
def validator(cls, fields):
for field in fields:
type_validator(field)
attr.s(field_transformer=validator)
class Data:
a: int
b: float
c: str
While I can add the validator to attrs-strict and have it work, the fact that the property is called field_transformer that is actually doing a validation seems counter-intuitive to me.
You could call it add_validator and it would make more sense semantically?
I really hope that we'll be able to make it much easier to build custom decorators though, when we ship our own mypy plugin.