Occasionally, when some code is defining a function, a -> will be added after the def line. This thing has a special term called type hint, which is type hint .
Official website: https://www.python.org/dev/peps/pep-0484/
such as:
def add(a:int, b:int) -> int:
return a+b
This representation is not so magical, it means: tell you the expected input type and output type . The type expected by the above code is int.
This website (https://mypy-lang.org, there is a wall) explains this feature:
In fact, it is the difference between dynamic definition and static definition of variable types . The same function can be omitted -> means dynamic definition and added -> means static definition.
For the above left function, the data type of n is not necessarily int, it can also be float and so on. . On the right, only int is limited.
This is the difference between static and dynamic.
I try to find the differences and advantages of the two. The following findings:
1. Changing a dynamic type function to a static type function does not speed up the calculation;
2. Even if you define int statically, no error will be reported when the input is float , and the output will not become the expected int type. So in use, there is no difference between dynamic and static types .
So this type hint looks rather tasteless.
Its uses are as follows:
1. Increase code readability;
2. It is easier to rewrite in other languages.