从类型输入中提取数据 [英] extracting data from typing types

查看:270
本文介绍了从类型输入中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除类型提示外,我在使用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]

现在我想

  1. 检查string_list是否符合string_list_class.
  2. 检查string_list_class是否为列表.
  3. 如果是,请检查该课程,以确保string_list_class是该课程的列表.
  1. Check if string_list conforms to string_list_class.
  2. Check if string_list_class is a list.
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆