Han*_*ans 8 python generics typing instanceof python-3.x
typing除了类型提示以外,我在使用Python中的类型时遇到了一些问题:
>>> from typing import List
>>> string_list = ['nobody', 'expects', 'the', 'spanish', 'inqusition']
>>> string_list_class = List[str]
Run Code Online (Sandbox Code Playgroud)
现在我想
string_list符合string_list_class。string_list_class为列表。string_list_class是一个列表。我发现自己无法实现以下任何一个目标:
>>> isinstance(string_list, string_list_class)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 708, in __instancecheck__
return self.__subclasscheck__(type(obj))
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 716, in __subclasscheck__
raise TypeError("Subscripted generics cannot be used with"
TypeError: Subscripted generics cannot be used with class and instance checks
>>> issubclass(string_list_class, List)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 716, in __subclasscheck__
raise TypeError("Subscripted generics cannot be used with"
TypeError: Subscripted generics cannot be used with class and instance checks
Run Code Online (Sandbox Code Playgroud)
该文档也并没有帮助。同样,API似乎不打算以这种方式使用,但是,我需要使用该功能。
我找到答案2的方法是
>>> type(string_list_class)
<class 'typing._GenericAlias'>
Run Code Online (Sandbox Code Playgroud)
艰难的我无权_GenericAlias自己创建它:
>>> _GenericAlias = type(List[str])
>>> isinstance(string_list_class, _GenericAlias)
True
Run Code Online (Sandbox Code Playgroud)
但是,这似乎根本不是一个好的解决方案,并且True对于诸如此类的其他类也有好处Collection。
对于1.和3.,我可以想象与repr(type(string_list))和一起黑客攻击某些东西,repr(string_list_class)并以某种方式将字符串与某物进行比较,但这并不是一个好的解决方案。
但是必须有更好的方法来做到这一点
lov*_*soa 16
要检查是否string_list符合string_list_class,您可以使用typeguard类型检查库。
from typeguard import check_type
try:
check_type('string_list', string_list, string_list_class)
print("string_list conforms to string_list_class")
except TypeError:
print("string_list does not conform to string_list_class")
Run Code Online (Sandbox Code Playgroud)
要检查是否string_list_class是列表类型,您可以使用typing_inspect库:
from typing_inspect import get_origin
from typing import List
get_origin(List[str]) # -> List
Run Code Online (Sandbox Code Playgroud)
您也可以使用私有__origin__字段,但没有稳定性保证。
List[str].__origin__ # -> list
Run Code Online (Sandbox Code Playgroud)
要检查类,即string_list_class列表,您可以再次使用typing_inspect库。
from typing_inspect import get_parameters
from typing import List
assert get_parameters(List[str])[0] == str
Run Code Online (Sandbox Code Playgroud)
和以前一样,如果您愿意冒险,也可以使用私人领域
List[str].__args__[0] # -> str
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1349 次 |
| 最近记录: |