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