#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.
0:04
What is a decorator?
0:05
I think the best way to explain it
0:07
is that a decorator can add behavior to a function,
0:10
so you pass the function into a decorator,
0:13
it can do something before and or after
0:16
and returns the newly decorated object.
0:19
And it's just one of those common design patterns
0:22
as described in design patterns
0:24
the elements of reusable object oriented software.
0:27
So let's import the modules we're going to use.
0:32
And let's define our first decorator.
0:35
Just a very basic one to show the syntax.
0:49
Alright, now you can use the mydecorator
0:52
to decoratate a function, and this is the syntax for that.
0:58
I will go into some of the details in a bit before,
1:01
example, why should you use wraps which is not required.
1:04
And the whole aspect of args and keyword args.
1:08
For now, at the very basic level, just remember,
1:11
a decorator takes you function, needs an inner function
1:15
to pass in the arguments and keyword arguments
1:18
and calls the function and see this sandwich effect here,
1:22
so you can do something before calling the function
1:25
and after it, so for example,
1:26
when you write a decorator to time your function,
1:29
here you would start the timing,
1:31
here you would call the function,
1:32
and here you would stop the timing.
1:34
You can look at it as adding behavior before
1:37
and after the function.
1:39
The function gets called, but additional logic
1:41
is added around it and that's what a decorator is for.
1:44
And then here is the syntax how to use it.
1:47
So right before the function you
1:50
use the at sign, @decorator.
1:52
If you have been using any web framework
1:55
like Flask for Django, you're familiar with this syntax.
1:58
As we will see towards the end,
2:00
there is a login required decorator for example in Django
2:04
that uses this concept of adding a behavior
2:07
which is that case is to see if the user is logged in
2:10
and it adds that behavior to a function
2:13
which is that case is usually the logic of a web page.
2:17
A route to a certain web page.
2:20
And keep in mind that this is just syntax,
2:23
the same thing could be written as...
2:27
So here you see actually that myfunction
2:31
gets passed into the decorator,
2:34
but this is the common way
2:35
how you would use a decorator.