+ 2
Saw this code somewhere, what is the significance of writing 'int' here?
def mult_two(a: int, b: int) -> int: return a*b
2 Antworten
+ 4
Type hints are not enforced, but they give some idea to the developer who wants to use this code, what kind of values must be passed to the function to make it work.
For example
mult_two('x', 'y')
does not result in syntax error, but it will cause a type error when the function is executed at runtime, because two strings cannot be multiplied.
There are also some utility tools that can analyse your code and give you heads up, if you violate these type restrictions. This can make Python safer to use in larger applications, reducing the bugs and errors that can be caused by Python's dynamic typing.
+ 5
It is called type hinting in Python. The arguments a and b are expected to accept integer type values and also return an integer.
https://docs.python.org/3/library/typing.html