Starting from Python 3.5, we have the option to statically indicate the type of a value in our Python code. Or in other words, type hint it.
"Type Hints" or annotations are a special syntax that allow declaring the type of a variable. In the below example, the x: int part means that the function expects an int object to be passed to the function; and the -> int means that the function will return an intobject.
def myFunc(x: int) -> int:
return x + x
# Type annotation on a function: accepts & returns strings
def greeting(first: str, last: str) -> str:
return 'Hello ' + first + " " last
# Type annotation in a variable: added in Python 3.6
name: str = "John"
The types aren't checked at runtime, though — when you run the Python script, the interpreter doesn't care about type hints.
Python is dynamically typed - it means that at the time of writing a program, you generally don't know what type a variable (or other expression) will be. Dynamic typing doesn't rid you of types. It just moves the responsibility of matching them onto the programmer.
Type annotations is about documenting our code by adding types to our parameters, return values etc. It does NOT change the functionality of the code, i.e. if I indicate that a variable is a string, the program won’t crash if I set it to an integer.
Type hints are useful on functions, to explain what the function takes as input and what it returns.
int, str, float, range, list etc are valid type hints.
Using type annotations, we can catch type mismatches before running our code, and editors and tools can give you better support. Type hints also enable you to use tools like mypy, that can check for errors that might have only been seen at runtime, as the type hints add a contract to your code that these tools can verify.
Type hints increase readability, code quality and allow you to find bugs and issues before your customers do.