使用 python 类型提示作为运行时类型检查(如果不同则引发 TypeError)

Kev*_*ata 5 python types assert type-hinting python-typing

我有一个示例函数:

from typing import Dict


def cool_func(foo: Dict[object, str], bar: bool, baz: float) -> None:
    foo_type_error_msg = "foo must be a Dict[object, str]"
    if not foo.isinstance(dict):
        raise TypeError(foo_type_error_msg)
    for s in foo.values():
        if not s.isinstance(str):
            raise TypeError(foo_type_error_msg)

    # the rest of the function
Run Code Online (Sandbox Code Playgroud)

如何使用类型提示中指定的类型在运行时检查变量?请注意,我不想对其他变量严格要求(只需检查参数foo)。

如果您想知道,我想强制执行该类型,以便错误(由错误类型引起的)不会出现在某处,the rest of the function并使用户与默认错误消息混淆。

我希望我能拥有这样的东西:

def cool_func(foo: Dict[object, str], bar: bool, baz: float) -> None:
    check_type('foo')
    # the rest of the function
Run Code Online (Sandbox Code Playgroud)

或者至少

def cool_func(foo: Dict[object, str], bar: bool, baz: float) -> None:
    check_type(foo, 'Dict[object, str]')
    # the rest of the function
Run Code Online (Sandbox Code Playgroud)