Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

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

does python 3.5 provide functions that allow to test whether a given argument would fit the type hints given in the function declaration?

if i have e.g. this function:

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

is there a python method that can check whether

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

fit the type hints?

i know that 'no type checking happens at runtime' but can i still check the validity of these arguments by hand in python?

or if python does not provide that functionality itself: what is the tool i'd need to use?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...