从类型输入中提取数据 [英] extracting data from typing types
问题描述
除类型提示外,我在使用Python中的typing
类型时遇到了一些问题:
I am having some issues working with the typing
types in Python for any more than type hinting:
>>> from typing import List
>>> string_list = ['nobody', 'expects', 'the', 'spanish', 'inqusition']
>>> string_list_class = List[str]
现在我想
- 检查
string_list
是否符合string_list_class
. - 检查
string_list_class
是否为列表. - 如果是,请检查该课程,以确保
string_list_class
是该课程的列表.
- Check if
string_list
conforms tostring_list_class
. - Check if
string_list_class
is a list. - If so, check the class, that
string_list_class
is a list of.
我发现自己无法实现以下任何一个目标
I find myself unable to achieve any of those:
>>> 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
文档对此并没有真正的帮助.同样,API似乎也不打算那样使用,但是,我需要使用该功能.
The documentation also is not really helpful with that. Also the API does not seem to be intended to be used that way, however, I need to use that functionality.
我找到答案2的一种方法是,
A way I found to answer 2. is, that
>>> type(string_list_class)
<class 'typing._GenericAlias'>
艰难的我无法访问_GenericAlias
我可以自己构建它:
Tough I have no access to _GenericAlias
I can build it myself:
>>> _GenericAlias = type(List[str])
>>> isinstance(string_list_class, _GenericAlias)
True
但是,这似乎根本不是一个好的解决方案,对于其他类(如Collection
),它也会产生True
.
However that does not seem like a good solution at all and it also yields True
for other classes like Collection
.
对于1.和3.,我可以想象与repr(type(string_list))
和repr(string_list_class)
一起入侵某事物,并以某种方式将该字符串与某事物进行比较,但这也不是一个好的解决方案.
For 1. and 3. I could imagine hacking something together with repr(type(string_list))
and repr(string_list_class)
and somehow comparing that string to something, but that also is not a good solution.
但是必须有更好的方法
推荐答案
检查变量是否符合键入对象
要检查string_list
是否符合string_list_class
,可以使用 typeguard 类型检查库
Checking if a variable conforms to a typing object
To check if string_list
conforms to string_list_class
, you can use the typeguard type checking library.
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")
检查打字对象的通用类型
要检查string_list_class
是否为列表类型,可以使用 typing_inspect 库:>
Checking the generic type of a typing object
To check if string_list_class
is a list type, you can use the typing_inspect library:
from typing_inspect import get_origin
from typing import List
get_origin(List[str]) # -> List
您也可以使用私有的__origin__
字段,但是并不能保证稳定性.
You could also use the private __origin__
field, but there is no stability guarantee for it.
List[str].__origin__ # -> list
检查打字对象的类型参数
要检查该类(是否为string_list_class
的列表),可以使用 typing_inspect 库再次.
Checking the type argument of a typing object
To check the class, that string_list_class
is a list of, you can use the typing_inspect library again.
from typing_inspect import get_parameters
from typing import List
assert get_parameters(List[str])[0] == str
和以前一样,如果您想冒险,也可以使用一个私有字段
As before, there is also a private field you can use if you like to take risks
List[str].__args__[0] # -> str
这篇关于从类型输入中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!