Книга: Practical Programming, Fourth Edition
Назад: Storing and Accessing Data in Lists
Дальше: Modifying Lists

Type Annotations for Lists

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

 >>>​​ ​​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 trick doesn’t prevent a programmer from calling the function with other kinds of data (even though this would often result in an error), but it does indicate what you expect when someone calls your function.

Назад: Storing and Accessing Data in Lists
Дальше: Modifying Lists