Type hints and the mypy program

Python 3 permits the use of type hints. The hints are present in assignment statements, function, and class definitions. They're not used directly by Python when the program runs. Instead, they're used by external tools to examine the code for improper use of types, variables, and functions. Here's a simple function with type hints:

def F(n: int) -> int:
if n in (0, 1):
return 1
else:
return F(n-1) + F(n-2)

print("Good Use", F(8))
print("Bad Use", F(355/113))

When we run the mypy program, we'll see an error such as the following:

Chapter_1/ch01_ex3.py:23: error: Argument 1 to "F" has incompatible type "float"; expected "int"

This message informs us of the location of the error: the file is Chapter_1/ch01_ex3.py, which is the 23rd line of the file. The details tell us that the function, F, has an improper argument value. This kind of problem can be difficult to see. In some cases, unit tests might not cover this case very well, and it's possible for a program to harbor subtle bugs because data of an improper type might be used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset