attrs icon indicating copy to clipboard operation
attrs copied to clipboard

Support for a validator argument to enable runtime validation

Open erikseulean opened this issue 4 years ago • 3 comments

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:
   ...

erikseulean avatar Dec 21 '20 22:12 erikseulean

Shouldn't that be possible with field_transformer? See https://www.attrs.org/en/stable/extending.html#automatic-field-transformation-and-modification

hynek avatar Dec 22 '20 04:12 hynek

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.

erikseulean avatar Dec 31 '20 12:12 erikseulean

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.

hynek avatar Dec 31 '20 13:12 hynek