PythiloLesson 5 of 15 · progress kept in this browser

Replacing flag arguments

What does format_name("Ada", "Lovelace", True) do? The caller cannot tell without opening the function. A boolean argument hides its meaning at the call site, and it often means the function does two different things.

There are two fixes.

  • If the flag picks between two behaviours, write two functions whose names say which: paid_orders(orders) and unpaid_orders(orders).
  • If it is a genuine option, make it keyword-only by putting * before it. Callers then have to write its name.
def format_name(first, last, *,
                last_first=False):
    if last_first:
        return f"{last}, {first}"
    return f"{first} {last}"

print(format_name("Ada", "Lovelace"))
print(format_name("Ada", "Lovelace",
                  last_first=True))

Now the call explains itself, and format_name("Ada", "Lovelace", True) raises TypeError instead of guessing.

Your task

Make format_amount(amount, *, currency=False, estimate=False) take both options by keyword only. Replace order_ids(orders, flag) with paid_ids(orders) and unpaid_ids(orders).