简体   繁体   English

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

[英]Is it possible to use type hint validation directly?

With version 3.6 python has type hints: 在3.6版中,python具有类型提示:

from typing import List, Union

def foo() -> List[Union[str, int]]:
    return 3

However can we use this syntax outside of intended scope? 但是,我们可以在预期范围之外使用此语法吗?
ie Can we use this syntax to validate some object? 即我们可以使用这种语法来验证某些对象吗?

objects = [['foo', 1], ['bar', 2.2]]
for object in objects:
    if not isinstance(object, List[Union[str, int]]):
        print(f'error, invalid object: {object}')

You can install the typeguard module : 您可以安装typeguard模块

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)

This outputs: 输出:

type of object[1] must be int; got float instead

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM