【发布时间】:2018-12-12 18:58:59
【问题描述】:
我在使用 Python 中的 typing 类型时遇到了一些问题,不仅仅是类型提示:
>>> 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是一个列表。
我发现自己无法实现其中任何一个:
>>> 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
documentation 对此也没什么帮助。此外,API 似乎并不打算以这种方式使用,但是,我需要使用该功能。
四处游荡
我发现回答 2. 的一种方法是,那个
>>> type(string_list_class)
<class 'typing._GenericAlias'>
虽然我无法访问_GenericAlias,但我可以自己构建它:
>>> _GenericAlias = type(List[str])
>>> isinstance(string_list_class, _GenericAlias)
True
但是,这似乎根本不是一个好的解决方案,它还会为其他类(如 Collection)生成 True。
对于 1. 和 3. 我可以想象用 repr(type(string_list)) 和 repr(string_list_class) 一起破解某些东西,并以某种方式将该字符串与某物进行比较,但这也不是一个好的解决方案。
但必须有更好的方法来做到这一点
【问题讨论】:
-
我明白了第 1 点,但第 2 点的目的是什么?如果
string_list符合string_list_class,那么您已经知道它是一个列表。我不知道第 3 点是什么意思。 -
我想检查
string_list_class是否是一个一般的列表类型。它可能是str、int、MyObject或其他内容的列表。这与 1 无关。对于 3,我想从List[MyObject]中提取MyObject。 -
好的,我明白了。但是...我不确定同时问 3 个几乎不相关的问题是否是个好主意...
-
我同意,但恕我直言,它们并非完全无关,对其中一两个问题的回答可以回答其他问题。我无法找到解决方案,但如果有,同一来源可能也可以回答其他问题。
标签: python python-3.x generics type-hinting instanceof