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

Create an isinstance version that works with the typing module #48

Open erikseulean opened 4 years ago

erikseulean commented 4 years ago

Currently, the isinstance check doesn't work with anything existing in the typing module.

For example, you can't do the following:

from typing import Dict
x = {'a': 'b'}
isinstance(x, Dict[str,str])

I think this could be fairly useful, especially if you're willing to do type checks beyond the "base type" such as checking the values of the keys in a dictionary.

Since attrs-strict already has the capability to do most of these checks, how about a derived library that simply provides an alternative isinstance that works with both python types and types provided in the typing module ?

Additionally (this might already exist) it could provide a decorator for functions that checks if the passed arguments are valid based on the types specified in the function declaration.

saytosid commented 4 years ago

Is there a generic enough API available that exposes the type-validation?

erikseulean commented 4 years ago

I don't think so, or at least I don't know about it.

saytosid commented 4 years ago

isinstance works with non-subscripted types -

>>> isinstance({}, Dict)
True
>>> isinstance({}, Dict[str, str])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/bb/lib/python3.7/typing.py", line 716, in __instancecheck__
    return self.__subclasscheck__(type(obj))
  File "/opt/bb/lib/python3.7/typing.py", line 724, in __subclasscheck__
    raise TypeError("Subscripted generics cannot be used with"
TypeError: Subscripted generics cannot be used with class and instance checks

I think it is a nice idea to provide an alternative that supports fully typed objects.

Instead of a derived library, How about a super library which can be used by attrs-strict and potentially many others 🙂

gaborbernat commented 2 years ago

Due to lack of interest in this issue and activity I'll close this for now as won't do.