Skip to content Skip to sidebar Skip to footer

Why Return Type Is Not Checked In Python3?

Example from PEP 484 -- Type Hints def greeting(name: str) -> str: return 'Hello ' + name Right way to call the function with str >>> greeting('John') 'Hello John'

Solution 1:

The abstract of the PEP states:

While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter. (While it would of course be possible for individual users to employ a similar checker at run time for Design By Contract enforcement or JIT optimization, those tools are not yet as mature.)

Solution 2:

This question might cause a bit confusion for newcomers to python3 type hints. There is no type checking support in python3. This means that python interpreter will not raise an exception if you pass incorrect type in arguments.

mypy can be used for in case you need this feature.

The actual reason for raising TypeError in examples above is unsafe use of (+) operator. If you change function provided in the examples using string formatting

def greeting(name: str) ->str:
    return'Hello {}'.format(name)

All of the above cases will work without raising TypeError, and no type checking will happen during runtime.

Type Hinting is used by IDEs like PyCharm, PyCharm Type Hinting, but it is just warnings showed by IDE, not by python interpreter.

Post a Comment for "Why Return Type Is Not Checked In Python3?"