#100DaysOfCode in Python Transcripts
Chapter: Days 22-24: Decorators
Lecture: Concepts: what did we learn
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Alright now it's time to review what we've learned, how to write a decorator. A decorator takes a function to be decorated.
0:10
It adds behavior before, and or, after. Then it returns the function. Don't forget to use wraps to the preserve the doc string. Args and keyword args.
0:22
There are various ways you can call a function in Python. The simplest way is to use a required, positional argument.
0:31
If I leave off this argument, I get an error. The second type, is the keyword argument which can be set to a default.
0:41
And then we have two arbitrary sequences which are the list, in this case sports, and keyword arguments which always go last.
0:50
Here is an example how you would call this with all the types of arguments. Let's write a timeit decorator. It takes a function, starts the timer
1:00
before calling the functions, calls the function, and ends the timer, printing how long the function took to execute. We define the decorator.
1:11
Here's how to apply it to a function. You can stack decorators. Note that the order matters. As timeit is the outer decorator,
1:24
that's the one that wraps at the outer level. Some examples of common decorators. Here are two from the Flask documentation.
1:33
One checks if a user's logged in and the other is performing caching. Those are ideal examples of decorators because they abstract away common behavior
1:44
which you want to apply to multiple functions. Here's another example of a well known decorator called LRU Cache. You can find those in the Flask
1:55
and the Python documentation respectively. And now it's your turn.