Decorators:
Python decorators allow you to change the behavior of a function without modifying the function
itself.
When to Use a Decorator in Python
You'll use a decorator when you need to change the behavior of a function without modifying the
function itself. A few good examples are when you want to add logging, test performance,
perform caching, verify permissions, and so on.
You can also use one when you need to run the same code on multiple functions. This avoids you
writing duplicating code.
Here are the building blocks used to create Python decorators
To get a better understanding of how decorators work, you should understand a few concepts
first.
• A function is an object. Because of that, a function can be assigned to a variable. The
function can be accessed from that variable.
Example:1
def my_function():
print('I am a function.')
# Assign the function to a variable without parenthesis. We don't want to execute the function.
description = my_function
# Accessing the function from the variable I assigned it to.
print(description())
OUTPUT:
I am a function.
None
How to Create a Python Decorator
,To create a decorator function in Python, I create an outer function that takes a function as an
argument. There is also an inner function that wraps around the decorated function.
Example: 2
Here is the syntax for a basic Python decorator:
def my_decorator_func(func):
def wrapper_func():
# Do something before the function.
func()
# Do something after the function.
return wrapper_func
# To use a decorator ,you attach it to a function like you see in the code below. We use a
decorator by placing the name of the decorator directly above the function we want to use it
on. You prefix the decorator function with an @ symbol.
@my_decorator_func
def my_func():
pass
Output: Empty space em radhu.
,Example: 3
Here is a simple example. This decorator logs the date and time a function is executed:
from datetime import datetime
def log_datetime(func):
'''Log the date and time of a function'''
def wrapper():
print(f'Function: {func.__name__}\nRun on: {datetime.today().strftime("%Y-%m-
%d %H:%M:%S")}')
print(f'{"-"*30}')
func()
return wrapper
@log_datetime
def daily_backup():
print('Daily backup job has finished.')
daily_backup()
OUTPUT:
Function: daily_backup
Run on: 2022-05-13 09:07:14
------------------------------
Daily backup job has finished.
Example: 4
How to Add Arguments to Decorators in Python
Decorators can have arguments passed to them. To add arguments to decorators I add *args and
**kwargs to the inner functions.
*args will take an unlimited number of arguments of any type, such as 10, True, or 'Brandon'.
**kwargs will take an unlimited number of keyword arguments, such as count=99,
is_authenticated=True, or name='Brandon'.
, Here is a decorator with arguments:
def my_decorator_func(func):
def wrapper_func(*args, **kwargs):
# Do something before the function.
func(*args, **kwargs)
# Do something after the function.
return wrapper_func
@my_decorator_func
def my_func(my_arg):
'''Example docstring for function'''
pass
# Decorators hide the function they are decorating. If I check the __name__ or __doc__ method
we get an unexpected result.
print(my_func.__name__)
print(my_func.__doc__)
OUTPUT:
wrapper_func
None
Python decorators allow you to change the behavior of a function without modifying the function
itself.
When to Use a Decorator in Python
You'll use a decorator when you need to change the behavior of a function without modifying the
function itself. A few good examples are when you want to add logging, test performance,
perform caching, verify permissions, and so on.
You can also use one when you need to run the same code on multiple functions. This avoids you
writing duplicating code.
Here are the building blocks used to create Python decorators
To get a better understanding of how decorators work, you should understand a few concepts
first.
• A function is an object. Because of that, a function can be assigned to a variable. The
function can be accessed from that variable.
Example:1
def my_function():
print('I am a function.')
# Assign the function to a variable without parenthesis. We don't want to execute the function.
description = my_function
# Accessing the function from the variable I assigned it to.
print(description())
OUTPUT:
I am a function.
None
How to Create a Python Decorator
,To create a decorator function in Python, I create an outer function that takes a function as an
argument. There is also an inner function that wraps around the decorated function.
Example: 2
Here is the syntax for a basic Python decorator:
def my_decorator_func(func):
def wrapper_func():
# Do something before the function.
func()
# Do something after the function.
return wrapper_func
# To use a decorator ,you attach it to a function like you see in the code below. We use a
decorator by placing the name of the decorator directly above the function we want to use it
on. You prefix the decorator function with an @ symbol.
@my_decorator_func
def my_func():
pass
Output: Empty space em radhu.
,Example: 3
Here is a simple example. This decorator logs the date and time a function is executed:
from datetime import datetime
def log_datetime(func):
'''Log the date and time of a function'''
def wrapper():
print(f'Function: {func.__name__}\nRun on: {datetime.today().strftime("%Y-%m-
%d %H:%M:%S")}')
print(f'{"-"*30}')
func()
return wrapper
@log_datetime
def daily_backup():
print('Daily backup job has finished.')
daily_backup()
OUTPUT:
Function: daily_backup
Run on: 2022-05-13 09:07:14
------------------------------
Daily backup job has finished.
Example: 4
How to Add Arguments to Decorators in Python
Decorators can have arguments passed to them. To add arguments to decorators I add *args and
**kwargs to the inner functions.
*args will take an unlimited number of arguments of any type, such as 10, True, or 'Brandon'.
**kwargs will take an unlimited number of keyword arguments, such as count=99,
is_authenticated=True, or name='Brandon'.
, Here is a decorator with arguments:
def my_decorator_func(func):
def wrapper_func(*args, **kwargs):
# Do something before the function.
func(*args, **kwargs)
# Do something after the function.
return wrapper_func
@my_decorator_func
def my_func(my_arg):
'''Example docstring for function'''
pass
# Decorators hide the function they are decorating. If I check the __name__ or __doc__ method
we get an unexpected result.
print(my_func.__name__)
print(my_func.__doc__)
OUTPUT:
wrapper_func
None