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

Feature request: Add validation option to auto_attribs #550

Closed
qpwo opened this issue Jul 10, 2019 · 3 comments
Closed

Feature request: Add validation option to auto_attribs #550

qpwo opened this issue Jul 10, 2019 · 3 comments

Comments

@qpwo
Copy link

qpwo commented Jul 10, 2019

This is just an idea. Some users of a library I work on use static analysis and other users don't, so we use both type hinting and validation on the attributes. We have several classes like this:

from attr.validators import instance_of
@attrs
class C:
    x: str = attrib(validator=instance_of(str))
    y: str = attrib(validator=instance_of(str))
    z: int = attrib(validator=instance_of(int))

And in this search you can see that most users of instance_of stick it on every attribute when they use it at all.

It would be nice if attrs had a kwarg like auto_attribs_with_validation that would convert the below class to the above class:

@attrs(auto_attribs_with_validation=True)
class C:
    x: str
    y: str
    z: int

Then of course if you executed c = C("foo", "bar", "baz") you would get a TypeError.

I'm aware that it may not be worth adding another kwarg to attrs.

If this is a good idea, then I can probably write the PR.

@qpwo
Copy link
Author

qpwo commented Jul 10, 2019

@rgabbard pointed out to me that some types cannot be fully instance-checked, e.g. all subscripted generics from typing, like List[int]. So auto_attribs_with_validation could do a few things:

Option A: Error out at class definition if there are any un-checkable types

Option B: Strip the subscripts off the generics, so

@attrs(auto_attribs_with_validation=True)
class C:
    nums: List[int]

would become

@attrs
class C:
    nums: List[int] = attrib(validator=instance_of(List)) # no [int]

and other sorts of un-checkable types would still error out.

Option C: Do nothing and let the user discover that their types are un-checkable.

@gabbard
Copy link
Member

gabbard commented Jul 10, 2019

@qpwo : This appears to basically be #301 updated for the existence of auto_attribs and type annotations.

@wsanchez
Copy link

Sounds like we agree this is a dup. I'm going to close this out as such.

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

No branches or pull requests

3 participants