Occasionally I see some code defining functions , stay def That line will be followed by a ->. There is a special term for this thing type hint, I.e. type prompt .
Official website :https://www.python.org/dev/peps/pep-0484/
such as :
def add(a:int, b:int) -> int:
return a+b
This expression is not so magical , intend : Tell you what type of input and output you expect . The expected type of the above code is int.
This website (https://mypy-lang.org, With walls ) This function is explained :
It's actually a variable type Dynamic definition and static definition The difference between . The same function can be used without -> Represents dynamic definition and addition -> Represents a static definition .
For the left function above , Yes n The data type of is not necessarily int, It can also be for float wait .. And the right side is limited to int.
This is the difference between static and dynamic .
I try to find the difference between the two and their respective advantages . There are the following findings :
1. Changing the dynamic type function to the static type function does not speed up the calculation ;
2. Even if you statically limit int, Input is float When it's time No mistake. , The output will not become the expected int type . So in use , There is no difference between static and dynamic types .
So this type hint It looks like a chicken ribs .
Its uses are as follows :
1. Increase code readability ;
2. It's easier to rewrite in other languages .