Is it possible to make python throw errors if the type of the argument passed to the annotated function does not match the specified?

One of the new features in python3.5 is a type hint. For example, the code below is valid:

def greeting(name: str) -> str:
    return 'Hello ' + name

But, as I understand it, it does not check anything on its own, and is also interpreted in exactly the same way as this:

def greeting(name):
    return 'Hello ' + name

and was implemented mainly to help static analyzers (and to simplify code understanding). But is there (or is planned to be implemented in the future) in any way (possibly using some third-party libraries) to make python throw errors when an argument of an invalid type is passed to a function with annotated argument types (using only hint type syntax)?

+5
2

PEP 0484, -:

- , get_type_hints() - , , . .

, Python , . , . - get_type_hints() , , , , , , . pzelasko, , . , , , , . Python 3.5 , , . , " ", PEP.

+4

, - :

def greeting(name):
    if type(name) is not str:
        raise TypeError('Expected str; got %s' % type(name).__name__)
    return 'Hello ' + name
0

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


All Articles