What are decorators in Python

Decorators in Python are a design pattern that allows you to modify the behavior of a function or method without changing its source code. This is done by defining a decorator function that wraps the original function and modifies its behavior in some way. Decorators can be applied to functions, methods, and even classes.

Here’s an example of a decorator that counts the number of times a function is called:

def count_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.num_calls += 1
print(f”Call {wrapper.num_calls} of {func.__name__!r}”)
return func(*args, **kwargs)

wrapper.num_calls = 0
return wrapper

@count_calls
def say_hello(name):
print(f”Hello, {name}!”)

say_hello(“Alice”)
say_hello(“Bob”)
say_hello(“Charlie”)

Below is the result when the aforementioned is executed run this code:

Call 1 of ‘say_hello’
Hello, Alice!
Call 2 of ‘say_hello’
Hello, Bob!
Call 3 of ‘say_hello’
Hello, Charlie!

This shows that the say_hello function has been called 3 times.

In this example, count_calls is a decorator factory. It creates and returns a decorator function that wraps the original function and modifies its behavior. The decorator function (wrapper) is defined inside the decorator factory (count_calls). This allows the decorator to keep track of the number of times the function has been called, even across multiple invocations.

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading