【问题标题】:How to check if a variables fits a custom type如何检查变量是否适合自定义类型
【发布时间】:2021-10-07 11:17:47
【问题描述】:

我有这个代码:

from typing import Tuple, Dict, List

CoordinatesType = List[Dict[str, Tuple[int, int]]]

coordinates: CoordinatesType = [
    {"coord_one": (1, 2), "coord_two": (3, 5)},
    {"coord_one": (0, 1), "coord_two": (2, 5)},
]

我想在运行时检查我的变量是否符合我的自定义类型定义。 我在想类似的东西:

def check_type(instance, type_definition) -> bool:
    return isinstance(instance, type_definition)

但显然isinstance 不起作用。 我需要在运行时检查它,实现它的正确方法是什么?

【问题讨论】:

  • 你要问的不是python运行时类型检查——也就是说,List[Dict[str, Tuple[int, int]]] 不是真正的类型,它是一个类型的注解 可以使用mypy 之类的东西静态检查正确性。要检查coordinates,您必须自己实现逻辑。
  • 尝试使用Typeguard,typeguard.readthedocs.io/en/latest

标签: python python-3.x custom-type typed python-3.10


【解决方案1】:

示例:

代码:

from typeguard import check_type
from typing import Tuple, Dict, List
coordinates = [
    {"coord_one": (1, 2), "coord_two": (3, 5)},
    {"coord_one": (0, 1), "coord_two": (2, 5)},
]
try:
    check_type('coordinates', coordinates, List[Dict[str, Tuple[int, int]]])
    print("type is correct")
except TypeError as e:
    print(e)

coordinates = [
    {"coord_one": (1, 2), "coord_two": ("3", 5)},
    {"coord_one": (0, 1), "coord_two": (2, 5)},
]
try:
    check_type('coordinates', coordinates, List[Dict[str, Tuple[int, int]]])
    print("type is correct")
except TypeError as e:
    print(e)

结果:

type is correct
type of coordinates[0]['coord_two'][0] must be int; got str instead

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 2021-10-26
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多