bloomberg / attrs-strict

Provides runtime validation of attributes specified in Python 'attr'-based data classes.
Apache License 2.0
52 stars 19 forks source link

Support PEP484 string annotations #45

Closed euresti closed 4 years ago

euresti commented 4 years ago

First off, I'm very excited that this project exists. We have something similar where I work thought ours only does one level isinstance checks. This is neat!

Is your feature request related to a problem? Please describe.

I noticed that type_validator supports auto_attribs=True out of the box:

@attr.s(auto_attribs=True)
class Foo:
    x: int = attr.ib(validator=type_validator())

Foo(5)
Foo("bad") # raises!

However, if you have complex types with forward references you might need to quote your annotations. e.g:

@attr.s(auto_attribs=True)
class Child:
    parent: "Parent" = attr.ib(validator=type_validator())

@attr.s(auto_attribs=True)
class Parent:
    pass

Child(Parent()) # raises a weird isinstance error.

Describe the solution you'd like I'm already working on a solution and can make a PR if you like. I'm just making sure that this is something you'd like to support. (It involves calling typing.get_type_hints() at the correct time.)

Describe alternatives you've considered pydantic handles forward refs slightly differently that what I'm thinking: https://github.com/samuelcolvin/pydantic/blob/e5fff9ccd06165c59d9dfc6126bc4b806ceb14b6/pydantic/typing.py#L143

Additional context Also if you need further motivation starting with python 3.10 all annotations will be strings anyway. (This of course won't affect attr.ib(type=str) style annotations.)

erikseulean commented 4 years ago

Thank you very much for this ❤️. I think it would be great to support types with forward references, it would make this library more complete!

Feel free to send a PR and we'll review asap.