Decorator
What is a Decorator?
- A decorator is a function that takes a function as a parameter, and adds additional responsibility/behaviour of the function (passed as parameter) and then returns it, without modifying that function explicitly.
- Decorators are also known as meta programming as it modifies scope of function at runtime.
Example: Let’s define a decorator function which decorates an existing function.
def decorate(function):
def additional():
print("Existing code got decorated")
function()
return additional
def existing():
print("Existing code")
existing= decorate(existing)
existing()
Output:
Python 3.8.4 (tags/v3.8.2:7b3cb59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 ================== RESTART: C:/Users/PC/Desktop/Hello.py ================ Existing code got decorated Existing code
- Python has syntax to simplify the decorator pattern which is called the “pie” syntax.
- Symbol @ is used to declare the decorators in Python as shown in below example
def decorate(function):
def additional():
print("Existing code got decorated")
function()
return additional
@decorate
def existing():
print("Existing code")
existing()
Output:
Python 3.8.4 (tags/v3.8.2:7b3cb59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 ================== RESTART: C:/Users/PC/Desktop/Hello.py ================ Existing code got decorated Existing code