如何检查变量是否适合自定义类型

2024-09-30 02:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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


Tags: instance代码fromtypingtypeonedictlist
1条回答
网友
1楼 · 发布于 2024-09-30 02:24:52

例如:

代码:

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

相关问题 更多 >

    热门问题