【发布时间】:2020-05-26 06:27:36
【问题描述】:
我正在使用 Python 从磁盘读取 JSON,并且正在尝试确保我的类型提示在下游是正确的。例如,像这样:
from typing import List
def verify_contains_ints(items: List[object]) -> List[int]:
for item in items:
if not isinstance(item, int):
raise TypeError("List contents must be all ints")
return items
我遇到的问题是我不想为 int、bool、str 等编写单独的函数。有没有办法动态指定我要验证的类型?我希望喜欢写的是这样的:
from typing import List
def verify_contains_type(items: List[object], inner_type = object) -> List[inner_type]:
for item in items:
if not isinstance(item, inner_type):
raise TypeError(f"List contents must be all {inner_type}s")
return items
在当前的类型提示状态下有没有办法做到这一点?
注意:这是我实际尝试做的简化版本。默认的 inner_type 在这里可能看起来很傻,但它对我的用例很重要。
【问题讨论】:
-
这还不是一个答案,但是在 python 3.9 之后的某个时间应该可以对参数化泛型进行更好的动态类型检查:python.org/dev/peps/pep-0585
标签: python type-hinting typing