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

问题描述 投票:1回答:1

在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}')
python types
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.