Test a helper with one edge case
Type one expression at a time and check its delimiters. · 172 words
An experiment collects confidence scores from a classifier and feeds each completed batch to a reporting function. For the scores 0.2, 0.6 and 1.0, the arithmetic mean is 0.6. The next batch contains no records at all. Dividing a total of zero by a count of zero would fail. The team agrees that the reporting function should return the Python value None for an empty batch. That preserves the difference between a batch containing no measurements and a batch whose measured scores all equal zero.
Write the expected results before trying the function. An empty list must return None, while the list [0.0] must return the number zero. In Python, the expression sum(scores) / len(scores) if scores else None implements that choice for a list called scores. The conditional expression selects the alternative before trying to divide. These two checks exercise a meaningful distinction in the report. If a later edit replaces None with zero, the empty-list test will catch the change even if every ordinary batch still produces the same mean.
Check your recall
Why should the empty list and the list [0.0] have different results in this report?
Check your answer
The empty list has no measurements and returns None. The one-item list has a measured score of zero and returns zero.
Sources and credits
Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.