0%

More Expressive Functions · practice

Pass a Function as a Value

So far, the in this chapter have received , numbers, , and None. A parameter can also receive a .

Start with an ordinary function that extracts a score from one attempt:

def score_of(attempt):
    return attempt["score"]

Adding parentheses calls the function and produces a score:

score_of(attempt)

Without parentheses, score_of refers to the function rather than running it:

score_of

That distinction lets one function receive another function and decide when to call it.

Tell sorted how to compare records

Python can sort simple numbers directly. An attempt dictionary contains several values, so sorted needs to know which one should control the order.

attempts = [
    {"learner": "Mina", "score": 8},
    {"learner": "Noah", "score": 6},
]


def score_of(attempt):
    return attempt["score"]


ranked = sorted(attempts, key=score_of, reverse=True)

The key receives score_of, not score_of(). During sorting, sorted calls score_of once for each attempt and uses the returned scores for comparison.

The sorting behavior is no longer fixed inside our code. We supply the function that selects the comparison .

Pass the choice through another function

We can make the choice itself a parameter. This general helper orders any records in ascending order:

def order_records(records, key_function):
    return sorted(records, key=key_function)

Now the same helper can order records by a name, a date, or another selected value. The code using order_records chooses the behavior by passing a suitable function. The exercise applies that design to a descending attempt ranking.

Which expression passes the function itself to sorted?

def score_of(attempt):
    return attempt["score"]

Let each call choose the ranking rule

Complete rank_attempts by passing key_function on to sorted. Do not hardcode a ; the function supplied with each call should decide what controls the ranking.

Task

Complete rank_attempts.

  • Return a new produced by sorted.

  • Pass key_function as the key.

  • Sort in descending order with reverse=True.

  • Do not call key_function yourself and do not change the original list.

The provided example ranks by score. Hidden checks supply a different key .