#100DaysOfCode in Python Transcripts
Chapter: Days 22-24: Decorators
Lecture: Quick primer on decorators

Login or purchase this course to watch this video and the rest of the course contents.
0:01 All right, a quick primer on decorators. What is a decorator? I think the best way to explain it is that a decorator can add behavior to a function,
0:11 so you pass the function into a decorator, it can do something before and or after and returns the newly decorated object.
0:20 And it's just one of those common design patterns as described in design patterns the elements of reusable object oriented software.
0:28 So let's import the modules we're going to use. And let's define our first decorator. Just a very basic one to show the syntax.
0:50 Alright, now you can use the mydecorator to decoratate a function, and this is the syntax for that. I will go into some of the details in a bit before,
1:02 example, why should you use wraps which is not required. And the whole aspect of args and keyword args.
1:09 For now, at the very basic level, just remember, a decorator takes you function, needs an inner function to pass in the arguments and keyword arguments
1:19 and calls the function and see this sandwich effect here, so you can do something before calling the function and after it, so for example,
1:27 when you write a decorator to time your function, here you would start the timing, here you would call the function,
1:33 and here you would stop the timing. You can look at it as adding behavior before and after the function. The function gets called, but additional logic
1:42 is added around it and that's what a decorator is for. And then here is the syntax how to use it. So right before the function you
1:51 use the at sign, @decorator. If you have been using any web framework like Flask for Django, you're familiar with this syntax.
1:59 As we will see towards the end, there is a login required decorator for example in Django that uses this concept of adding a behavior
2:08 which is that case is to see if the user is logged in and it adds that behavior to a function which is that case is usually the logic of a web page.
2:18 A route to a certain web page. And keep in mind that this is just syntax, the same thing could be written as...
2:28 So here you see actually that myfunction gets passed into the decorator, but this is the common way how you would use a decorator.


Talk Python's Mastodon Michael Kennedy's Mastodon