在3.6版本中,python有类型提示:
from typing import List, Union
def foo() -> List[Union[str, int]]:
return 3
但是,我们可以在预期范围之外使用此语法吗? 即我们可以使用此语法来验证某些对象吗?
objects = [['foo', 1], ['bar', 2.2]]
for object in objects:
if not isinstance(object, List[Union[str, int]]):
print(f'error, invalid object: {object}')
你可以安装typeguard
module:
from typeguard import check_type
from typing import Tuple
objects = [('foo', 1), ('bar', 2.2)]
for object in objects:
try:
check_type('object', object, Tuple[str, int])
except TypeError as e:
print(e)
这输出:
type of object[1] must be int; got float instead