attrs icon indicating copy to clipboard operation
attrs copied to clipboard

Is it possible to validate all attribute types by default?

Open paketb0te opened this issue 1 year ago • 0 comments

Sorry if this is a dumb question, I have read the docs section on validators and searched the github issues, but did not find an answer...

Is there a way to make a class use the instance_of validator on all its attributes, without specifying the validator separately for each attribute?

So instead of doing this:

@define()
class Foo:
    bar: str = field(validator=instance_of(str))
    baz: int = field(validator=instance_of(int))


foo = Foo(bar=False, baz=123)
# TypeError: ("'bar' must be <class 'str'> (got False that is a <class 'bool'>).", ...)

Is there something like this:

@define(validate_attribute_types=True)
class Foo:
    bar: str
    baz: int


foo = Foo(bar=False, baz=123)
# TypeError: ("'bar' must be <class 'str'> (got False that is a <class 'bool'>).", ...)

The first example obviously works just fine and does exactly what one would expect, I just imagine that there are a lot of cases where people want the instance_of validator on all attributes, and since attrs is all about removing boilerplate, I guess I am not the first one who would have a "validate types by default" option :)

In any case, thanks a lot for this great library!

paketb0te avatar Mar 05 '24 17:03 paketb0te