有没有内置的方法或最佳实践来使用typing
库检查容器类型?
我想看看:
from typing import List
isinstance([1,2,3], List[int])
一般问题是使用相同语法的不同行为:
In [22]: isinstance([1,2], List)
Out[22]: True
In [23]: isinstance([1,2], List[int])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-8598eb948ef8> in <module>()
----> 1 isinstance([1,2], List[int])
/usr/lib/python3.7/typing.py in __instancecheck__(self, obj)
706
707 def __instancecheck__(self, obj):
--> 708 return self.__subclasscheck__(type(obj))
709
710 def __subclasscheck__(self, cls):
/usr/lib/python3.7/typing.py in __subclasscheck__(self, cls)
714 if cls._special:
715 return issubclass(cls.__origin__, self.__origin__)
--> 716 raise TypeError("Subscripted generics cannot be used with"
717 " class and instance checks")
718
TypeError: Subscripted generics cannot be used with class and instance check```