14

python 3.5 是否提供允许测试给定参数是否符合函数声明中给出的类型提示的函数?

如果我有这个功能:

def f(name: List[str]):
    pass

有没有python方法可以检查是否

name = ['a', 'b']
name = [0, 1]
name = []
name = None
...

符合类型提示?

我知道'在运行时不进行类型检查',但我仍然可以在 python 中手动检查这些参数的有效性吗?

或者如果 python 本身不提供该功能:我需要使用什么工具?

4

2 回答 2

18

Python 本身不提供此类功能,您可以在此处阅读更多信息:


我为此写了一个装饰器。这是我的装饰器的代码:

from typing import get_type_hints

def strict_types(function):
    def type_checker(*args, **kwargs):
        hints = get_type_hints(function)

        all_args = kwargs.copy()
        all_args.update(dict(zip(function.__code__.co_varnames, args)))

        for argument, argument_type in ((i, type(j)) for i, j in all_args.items()):
            if argument in hints:
                if not issubclass(argument_type, hints[argument]):
                    raise TypeError('Type of {} is {} and not {}'.format(argument, argument_type, hints[argument]))

        result = function(*args, **kwargs)

        if 'return' in hints:
            if type(result) != hints['return']:
                raise TypeError('Type of result is {} and not {}'.format(type(result), hints['return']))

        return result

    return type_checker

你可以这样使用它:

@strict_types
def repeat_str(mystr: str, times: int):
    return mystr * times

虽然限制你的函数只接受一种类型并不是很pythonic。尽管您可以使用abc(抽象基类)number(或自定义 abc)作为类型提示,并限制您的函数不仅接受一种类型,而且接受您想要的任何类型组合。


如果有人想使用它,请为其添加一个 github 存储库。

于 2015-09-29T13:04:06.680 回答
9

这是一个老问题,但是我编写了一个工具来根据类型提示进行运行时类型检查:https ://pypi.org/project/typeguard/

于 2016-12-09T23:38:19.653 回答