Paul's Python CoursePPC

Project 18 of 20, for Caitlin

Timing and Retry Decorators

Two decorators for the till on the fruit table at Caitlin's bake sale: one times every call and finds the slow one, one tries the card reader again when it doesn't answer.

About an hour and a half, in 16 steps.

Sign up free to open itLog in

Act 2 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • CaitlinThe bake sale's got a fruit table now, but the till weighs everything and it's really slow.
  • YahyaI timed it at four minutes for two plums, and the queue went right past the next stall.
  • CaitlinMy till has a function for everything, and one of them is dawdling. I want to know which.
  • YahyaAnd the card reader only answers if you ask it twice, so Caitlin asks it twice, out loud.
  • PaulDon't guess which one's slow, measure it, and let the till do the asking twice.

Write a decorator timed that times a function every time it runs, appends (name, seconds) to the list log, and hands back the function's own result. Read the time with clock(): it starts as time.perf_counter, and the checks swap it for a clock that ticks in known steps.

Put @timed on the till's three functions. Then write two helpers for the report:

  • slowest(entries, count): a list of the names of the count slowest calls, slowest first
  • slow_calls(entries, limit): a list of the entries that took longer than limit seconds, in the order they happened

Then a second decorator, retry, for the card reader. When the function raises a ConnectionError, it calls it again, up to TRIES calls in all, and hands back the first answer that comes. If the last try fails too, the error comes out. Any other error comes straight out, with no second go. Put @retry on take_card.

What it prints
Plums: £3.15
Leeks: £1.80
Figs: £1.60
Paid £6.55 by card
Slowest: ['look_up_price']
look_up_price took 0.30 s
look_up_price took 0.30 s
look_up_price took 0.30 s

What you learn

What's in it

  1. A function is a value
  2. A function is a value
  3. Sorting by what matters
  4. A function on one line
  5. The slowest call
  6. Keep some, change each
  7. Sorting by what matters
  8. A function that remembers
  9. A function that remembers
  10. Wrapping a function
  11. The @ line
  12. How Paul would do it
  13. Fix Riya's version
  14. Make the decorators
  15. Ship it