Programming language can be either statically typed or dynamically typed. Languages that use static typing require programmer to explicitly define a data type of a variable. Python is a dynamically typed language, meaning data type doesn’t need to be explicitly defined and it can even change during runtime.

Just like with most of things, there are negatives and positives to both. Dynamic typing might be easier and faster, but it’s a lot easier to cause bugs in your program.

Type hints offer optional static typing. You can use type hints to define the expected data type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# parameter separated by :, return value by ->
def describeNumber(number: int) -> str:
	if number % 2 == 1:
		return 'An odd number.'
	elif number == 42:
		return 'The answer.'
	else:
		return 'Yes, that is a number.'

my_lucky_number: int = 42
print(describeNumber(my_lucky_number))

Using Type hints allows you to test your code during development and to avoid potential bugs caused by returning values of a different data type than expected.

There is one catch - as of right now, Python doesn’t have a built-in Type hints analyzer. For that you would have to install a 3rd party library. Current industry standard is to use Mypy.

Mypy is a Static analysis tool, that analyzes code before the program runs.

Possible output when the return data type is different than expected data type:

1
C:\Users\User\Desktop>python m mypy example.py Incompatible types in assignment (expression has type "float", variable has type "int") Found 1 error in 1 file (checked 1 source file)

Type Hints can be used even in more complex situations, such as when dealing with a data structure containing multiple different data types.