是否可以直接使用类型提示验证?

时间:2019-02-16 06:12:36

标签: python types

在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}')

1 个答案:

答案 0 :(得分:2)

您可以安装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