python 3.5 type hints: can i check if function arguments match type hints?

好久不见. 提交于 2019-11-29 04:22:31
Ilya Peterov

Python itself doesn't provide such functions, you can read more about it here:


I wrote a decorator for that. This is the code of my decorator:

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

You can use it like that:

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

Though it's not very pythonic to restrict your function to accept only one type. Though you can use abc (abstract base classes) like number (or custom abc) as type-hints and restrict your functions to accept not only one type, but whatever combination of types you want.


Added a github repo for it, if anybody wants to use it.

This is an old question, but there is a tool I've written for doing run time type checking based on type hints: https://pypi.org/project/typeguard/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!