The Basics
Functions and methods are not limited to datatype variables as arguments. Functions can be passed as an argument as well. You can wrap your function with more functionality. Seemingly complex, this capability actually simplifies some tasks.
def someDecoratorFunction(func):
def wrapper():
print('This happens before')
func()
print('This happens after')
return wraper
@someDecoratorFunction
def simpleFunction():
print('this is a decorated function')
simpleFunction()
#Result
# This happens before
# this is a decorated function
# This happens after
Lets unpack what's going on here. First we defined a function called "someDecoratorFunction" which takes a function as an argument. Within that function we defined "wrapper" which effectively defines how our decorator operates. This wrapper is finally returned. Â
The "simpleFunction" is decorated with our decorator function and when it is called on line 12, it is passed to the decorator for further evaluation. Syntactically, is the same as someDecorator(simpleFunction)Â
This allows for some unique and very powerful ways to compose your script. The decorators can be defined in an external module and used anywhere within your code. For example, if you have a function that should only be run within a specific time of day, you could use something similar to the following.
from datetime import datetime
def onlyDayTime(func):
def wrapper():
if 7 <= datetime.now().hour < 22: # If after 0700 and before 2200
funct()
else:
pass # Do nothing
return wrapper
@onlyDayTime
def yell(text):
print(text.upper())
yell('python rules')