Книга: Practical Programming, Fourth Edition
Назад: Omitting a return Statement: None
Дальше: What Did You Call That?

Dealing with Situations That Your Code Doesn’t Handle

You’ll often write a function that works only in some situations. For example, you might write a function that takes as a parameter the number of people who want to eat a pie and returns the percentage of the pie that each person gets to eat. If there are five people, each person gets 20% of the pie; if there are two people, each person gets 50%; if there is one person, that person gets 100%; but if there are zero people, what should the answer be?

Here is an implementation of this function:

​ ​def​ ​pie_percent​(n: int) -> int:
​  ​"""Return the percentage of a pie that each person gets to eat if n​
​ ​ people are sharing the pie.​
​ 
​ ​ >>> pie_percent(5)​
​ ​ 20​
​ ​ >>> pie_percent(2)​
​ ​ 50​
​ ​ >>> pie_percent(1)​
​ ​ 100​
​ 
​ ​ """​
​ 
​  ​return​ int(100 / n)

Reading the code, if someone calls pie_percent(0), then this will result in a ZeroDivisionError. There isn’t anything that anyone can do about this situation; there isn’t a sensible answer.

As a programmer, you warn other people about situations that your function isn’t set up to handle by describing your assumptions in a precondition. Here is the same function with a precondition:

​ ​def​ ​pie_percent​(n: int) -> int:
​  ​"""Assuming there are n people who want to eat a pie, return the​
​ ​ percentage of the pie that each person gets to eat.​
​ 
​ ​ Precondition: n > 0​
​ 
​ ​ >>> pie_percent(5)​
​ ​ 20​
​ ​ >>> pie_percent(2)​
​ ​ 50​
​ ​ >>> pie_percent(1)​
​ ​ 100​
​ 
​ ​ """​
​ 
​  ​return​ int(100 / n)

If your function expects certain parameter values, add a precondition to warn others

Whenever you write a function and you’ve assumed something about the parameter values, write a precondition that lets other programmers know your assumptions. If they ignore your warning and call it with invalid values, the fault does not lie with you!

Назад: Omitting a return Statement: None
Дальше: What Did You Call That?