Decorators can be used to slow code down. Slowing down code can be useful when working with web services or when you want to rate limit a function. In this lesson, you’ll see how to create a @slow_down decorator that sleeps one second before it calls the decorated function.
Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Slowing Down Code With Decorators
00:00 Now that you’ve done the debugging, what if you need to slow a function down? How could this be useful? You could be troubleshooting an API, accessing information over a network, or maybe you simply need to put a function into a wait state.
00:14
So you could have a handy, ready-made decorator to use in these circumstances. Back in the decorators module, go ahead and copy the boilerplate decorator.
00:29
Place it below your last one, debug().
00:35
Just as a note, if you’ve skipped around, this decorator will require the import of time also, so make sure that’s still there. This new decorator will be named slow_down().
00:47
It will receive a function. It will """Sleep 1 second before calling the function"""—put that in your docstring. Rename the wrapper—wrapper_slow_down().
01:00
Using time, that you’ve imported from the standard library, use the sleep() method and enter into it 1 second.
01:14
And this time, simply return the function that you’re wrapping here with its *args and **kwargs. Lastly, return wrapper_slow_down.
01:24
That’s it! Save. Switch back to examples.py. Again, this one is importing all of the decorators. In the examples module, use your new @slow_down decorator and make a simple countdown().
01:47
It’ll accept as an argument a from_number.
01:57 So here, it’s going to do a little bit of recursive functionality…
02:05
calling itself, again, using the current from_number - 1. So again, you’re defining countdown(), starting with an integer as a from_number.
02:18
If the from_number is less than 1, it’ll print "Liftoff!". else: it’ll print the current from_number and then run countdown()—or call countdown(), again, with from_number - 1.
02:31
And remember, each of those calls is decorated by @slow_down. Let’s save. So as you can see here, your decorator is showing the docstring, which is nice.
02:43
It’s going to Sleep 1 second before calling the function each time. Okay. Save, enter into your REPL, and from examples import countdown.
02:55
Great, that worked fine. Inspect countdown—it’s a function. That all looks great. All right. To run it, enter in countdown() and put an argument of a number of seconds—in this case, 3.
03:15 That worked perfect. So, controlling the rate that functions get called could be very useful if you’re accessing services from the internet, like troubleshooting an API.
Become a Member to join the conversation.