This lesson introduces decorators, functions that take other functions and extend their behavior without explicitly modifying them. You’ll see what decorators are and how they work. The examples in the lesson will also show you how to decorate your own functions.
The argument will be named
func. Next, you will create another function without any arguments that’s simply a wrapper. In its statement, it’ll start off with printing
"Something is happening before the function is called". That function that was passed in as the argument will then be called just below that, and then another print statement.
This side gets evaluated first, so
say_whee, the function, gets passed into
my_decorator(), so it travels into here, and then it’s wrapped inside of these two print statements and gets called here.
say_whee used to simply just print out
"Whee!". But now, instead of just printing that, it will print this statement first—
Something is happening before the function is called., and run the function, and then
Something is happening after the function is called. All this code wrapping around your internal function.
You’re going to create a decorator that can wrap around another function and tell it what time of day it is to determine if it should run or not. So in this case, you’re defining this decorator
not_during_the_night() and passing it, as an argument,
So, this is a fun little statement.
datetime.now() is going to call the current time and then return just the
.hour portion of that
datetime.now(), and if this is between, in this case, equal to or greater than
7, and less than—in this case, military time—10:00 PM, call
pass. Pass on that.
say_whee(), the function. Again, it prints a very ecstatic
"Whee!", which shouldn’t happen at nighttime. Okay. If you were to call out
say_whee(), it’ll scream
Whee!, but if we wanted to protect our neighbors’ sanity and our relationship with them, we can decorate it and say, “This function should only be called during the day—not during the night.” And in this case, we pass our function
say_whee into it, so
say_whee()—this function right here—is getting decorated by
not_during_the_night(), wrapped around this code right here with this conditional statement, and being reassigned here.
say_whee now is a
function with a reference to
not_during_the_night, and you can call it because it depends what time of day it is wherever you are right now, running this. In my case, it’s the daytime.
06:00 So we can have some fun. All right! There’s your first look at decorating. Let’s go a little bit further and make decorators a little more readable, a little easier to spot, with some syntactic sugar.
Become a Member to join the conversation.