Decorator in Python
Decorators in Python are employed to enhance functions by adding features such as logging, authorization, caching, validation, memoization, timing etc
def decorator(func):
def wrapper:
print(f"Before the function.")
func()
print(f"After the function.")
return wrapper
# Tells the function, it is a decorator.
@decorator
def hello():
print("Hello, World!")
# Call the function
hello()
The provided Python code defines a decorator named decorator
that takes a function func
as its argument. The decorator encapsulates the original function's behavior within a wrapper function. This wrapper function, when invoked, prints a message before and after calling the original function. The intention is to augment the functionality of any decorated function. Following the decorator definition, the code applies the @decorator
syntax to the hello
function, signaling that it should be decorated by the decorator
function. When the hello
function is subsequently called, it not only prints "Hello, World!" but also executes the additional behavior defined in the wrapper, showcasing the extended capabilities introduced by the decorator.
ย