如何检查变量是否适合自定义类型
How to check if a variables fits a custom type
我有这个代码:
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
是行不通的。
我需要在运行时检查它,正确的实现方式是什么?
- 尝试使用
Typeguard
:https://typeguard.readthedocs.io/en/latest/userguide.html#using-type-checker-functions
示例:
代码:
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
我有这个代码:
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
是行不通的。
我需要在运行时检查它,正确的实现方式是什么?
- 尝试使用
Typeguard
:https://typeguard.readthedocs.io/en/latest/userguide.html#using-type-checker-functions
示例:
代码:
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