您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python 3.5类型提示:我可以检查函数参数是否匹配类型提示吗?

python 3.5类型提示:我可以检查函数参数是否匹配类型提示吗?

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。虽然您可以使用abcnumber自定义abc)之类的abc(抽象基类)作为类型提示,并限制您的函数不仅接受一种类型,还可以接受所需类型的任意组合。

如果有人要使用它,请添加一个github存储

python 2022/1/1 18:30:00 有190人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶