Python type hints: can I check if function arguments match type hints?

Does python 3.5 provide functions to check if a given argument will match the types specified in the function declaration?

if I have, for example, this function:

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

is there a python method that can verify that

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

match the types of hints?

I know that "type checking does not happen at runtime", but can I verify the validity of these arguments manually in python?

or if python does not provide this functionality: which tool would I use?

+4
source share
2 answers

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 repo, - .

+6

Source: https://habr.com/ru/post/1609477/


All Articles