Understanding Python Decorators

a

admin

October 25, 2025

Python Decorators: A Deep Dive

Decorators are a powerful feature in Python that allow you to modify the behavior of functions or classes without permanently modifying their code.

What is a Decorator?

A decorator is a function that takes another function as an argument and extends or alters its behavior without explicitly modifying it.

Basic Decorator Example

```python def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper

@my_decorator def say_hello(): print("Hello!")

say_hello() ```

Decorators with Arguments

```python def repeat(num_times): def decorator_repeat(func): def wrapper(args, kwargs): for _ in range(num_times): result = func(args, **kwargs) return result return wrapper return decorator_repeat

@repeat(num_times=3) def greet(name): print(f"Hello {name}")

greet("Alice") ```

Class Decorators

```python class CountCalls: def init(self, func): self.func = func self.num_calls = 0

def __call__(self, *args, **kwargs):
    self.num_calls += 1
    print(f"This is executed {self.num_calls} times")
    return self.func(*args, **kwargs)

@CountCalls def say_hello(): print("Hello!")

say_hello() say_hello() ```

Common Use Cases

  1. Timing functions
  2. Logging
  3. Access control
  4. Caching
  5. Rate limiting