1

我有这个代码:

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是行不通的。我需要在运行时检查它,实现它的正确方法是什么?

4

1 回答 1

3

例子:

代码:

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
于 2021-08-02T03:12:42.020 回答