smarie / python-pyfields

Define fields in python classes. Easily.
https://smarie.github.io/python-pyfields
BSD 3-Clause "New" or "Revised" License
45 stars 10 forks source link

`check_type` does not work with Subscripted generic fields #46

Closed devashishshankar closed 4 years ago

devashishshankar commented 4 years ago

If I have a field with type_hint being something like List[A], and check_type=True, I would expect it to validate the field. However, the code throws the following error on class init:

TypeError: Subscripted generics cannot be used with class and instance checks

This seems to be the default behavior of isinstance when dealing with any subscripted generic field, for e.g. List[str] or Optional[str]. See related SO answer. Consequently validate also suffers with the same issue.

There is an easy workaround, setting check_type=False, and adding a custom validator:

f = field(type_hint=List[A], check_type=False,
              validators=lambda l: isinstance(l, list) and all([isinstance(e, A) for e in l]),)

However, I still thought I would add this issue in case someone runs into it. (Don't know if this should be handled at a library level, given this is a limitation of the default isinstance)

smarie commented 4 years ago

As mentioned in this doc section, pyfields relies on whatever type checking library is available on your machine.

So if you have typeguard or pytypes installed, it should work correctly.

devashishshankar commented 4 years ago

Ah, thanks! typeguard works but is python3 only. And pytypes doesn't work for py3.7. But these are already open issues in those libraries.