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?
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 formattingAll 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.
The abstract of the PEP states: