Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to validate all attribute types by default? #1254

Open
paketb0te opened this issue Mar 5, 2024 · 0 comments
Open

Is it possible to validate all attribute types by default? #1254

paketb0te opened this issue Mar 5, 2024 · 0 comments

Comments

@paketb0te
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant