Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return type is not checked in python3? [duplicate]

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'

If I call it with int:

>>> greeting(2)
TypeError: must be str, not int

Call with list

>>> greeting(["John"])
TypeError: must be str, not list

Everything works fine right? greeting function always accepts str as a parameter.

But if I try to test function return type, for example, use the same function but change return type to int.

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

Function returns str but type is defined as int, and no exception is raised:

>>> greeting("John")
'Hello John'

Another example:

def greeting(name: str) -> str:
    return len(name)

>>> greeting("John")
4

Although PEP 484 says that return type is expected to be str, it is not actually analogical to argument type check which can be seen in above examples.

This states that the expected type of the name argument is str. Analogically, the expected return type is str.

Am I missing something or there is no type check for return type?

like image 283
demonno Avatar asked Aug 25 '17 07:08

demonno


2 Answers

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.)

like image 102
strippenzieher Avatar answered Nov 20 '22 10:11

strippenzieher


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.

like image 3
demonno Avatar answered Nov 20 '22 10:11

demonno