Type Annotations for Lists

When writing type contracts for functions, often we’ll want to specify that the values in a list parameter are all of a particular type. For example, we might write a function to calculate the average of a list of floats:

 >>>​​ ​​def​​ ​​average(L:​​ ​​list)​​ ​​->​​ ​​float:
 ...​​ ​​"""Return the average of the values in L.
 ...
 ... >>> average([1.4, 1.6, 1.8, 2.0])
 ... 1.7
 ... """

There is currently no indication that the function works only with lists of numbers, but it would be odd to call it with a list of strings, for example. To address this, Python includes module typing that allows us to specify the expected type of value contained in a list (and in other types that you’ll encounter in Chapter 10, Reading and Writing Files and Chapter 11, Storing Data Using Other Collection Types). In order to prevent conflicts with type list, this module contains a capitalized version, List, that we can use in the type annotation:

 >>>​​ ​​from​​ ​​typing​​ ​​import​​ ​​List
 >>>​​ ​​def​​ ​​average(L:​​ ​​List[float])​​ ​​->​​ ​​float:
 ...​​ ​​"""Return the average of the values in L.
 ...
 ... >>> average([1.4, 1.6, 1.8, 2.0])
 ... 1.7
 ... """

This doesn’t prevent a programmer from calling our function with other kinds of data (even though this would often result in an error), but it does indicate what we expect when someone calls our function.

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

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