[Avg. reading time: 14 minutes]
Decorator
Decorators in Python are a powerful way to modify or extend the behavior of functions or methods without changing their code. Decorators are often used for tasks like logging, authentication, and adding additional functionality to functions. They are denoted by the “@” symbol and are applied above the function they decorate.
def say_hello():
print("World")
say_hello()
How do we change the output without changing the say hello() function?
wrapper()
is not reserved word. It can be anyting.
Use Decorators
# Define a decorator function
def hello_decorator(func):
def wrapper():
print("Hello,")
func() # Call the original function
return wrapper
# Use the decorator to modify the behavior of say_hello
@hello_decorator
def say_hello():
print("World")
# Call the decorated function
say_hello()
If you want to replace the new line character and the end of the print statement, use end=''
# Define a decorator function
def hello_decorator(func):
def wrapper():
print("Hello, ", end='')
func() # Call the original function
return wrapper
# Use the decorator to modify the behavior of say_hello
@hello_decorator
def say_hello():
print("World")
# Call the decorated function
say_hello()
Multiple functions inside the Decorator
def hello_decorator(func):
def first_wrapper():
print("First wrapper, doing something before the second wrapper.")
#func()
def second_wrapper():
print("Second wrapper, doing something before the actual function.")
#func()
def main_wrapper():
first_wrapper() # Call the first wrapper
second_wrapper() # Then call the second wrapper, which calls the actual function
func()
return main_wrapper
@hello_decorator
def say_hello():
print("World")
say_hello()
Args & Kwargs
*args
: This is used to represent positional arguments. It collects all the positional arguments passed to the decorated function as a tuple.**kwargs
: This is used to represent keyword arguments. It collects all the keyword arguments (arguments passed with names) as a dictionary.
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Positional Arguments (*args):", args)
print("Keyword Arguments (**kwargs):", kwargs)
result = func(*args, **kwargs)
return result
return wrapper
@my_decorator
def example_function(a, b, c=0, d=0):
print("Function Body:", a, b, c, d)
# Calling the decorated function with different arguments
example_function(1, 2)
example_function(3, 4, c=5)
Popular Example
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Execution time of {func.__name__}: {end - start} seconds")
return result
return wrapper
@timer
def add(x, y):
"""Returns the sum of x and y"""
return x + y
@timer
def greet(name, message="Hello"):
"""Returns a greeting message with the name"""
return f"{message}, {name}!"
print(add(2, 3))
print(greet("Rachel"))
The purpose of @wraps
is to preserve the metadata of the original function being decorated.
Practice Item
from functools import wraps
# Decorator without @wraps
def decorator_without_wraps(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
# Decorator with @wraps
def decorator_with_wraps(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
# Original function with a docstring
def original_function():
"""
This is the original function's docstring.
"""
pass
# Decorate the original function
decorated_function_without_wraps = decorator_without_wraps(original_function)
decorated_function_with_wraps = decorator_with_wraps(original_function)
# Display metadata of decorated functions
print("Without @wraps:")
print(f"Name: {decorated_function_without_wraps.__name__}")
print(f"Docstring: {decorated_function_without_wraps.__doc__}")
print("\nWith @wraps:")
print(f"Name: {decorated_function_with_wraps.__name__}")
print(f"Docstring: {decorated_function_with_wraps.__doc__}")
Memoization
Memoization is a technique used in Python to optimize the performance of functions by caching their results. When a function is called with a particular set of arguments, the result is stored. If the function is called again with the same arguments, the cached result is returned instead of recomputing it.
Benefits
Improves Performance: Reduces the number of computations by returning pre-computed results.
Efficient Resource Utilization: Saves computation time and resources, especially for recursive or computationally expensive functions.
git clone https://github.com/gchandra10/python_memoization