šŸ

Decorators: Enhancing Functions

Advanced
120 XP
50 min
Lesson Content

Decorators: Powerful Function Modifiers

Decorators are a powerful feature in Python that allow you to modify or enhance functions without changing their code. They're widely used in frameworks like Flask and Django.

What are Decorators?

Decorators are functions that wrap other functions, adding functionality before or after execution.

Basic Decorator

# Simple decorator
def my_decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

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

say_hello()
# Output:
# Before function
# Hello!
# After function

Decorator with Arguments

def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
# Output: (printed 3 times)
# Hello, Alice!

Built-in Decorators

# @staticmethod - doesn't need self
class Math:
    @staticmethod
    def add(a, b):
        return a + b

# @classmethod - receives class as first argument
class Person:
    count = 0
    
    @classmethod
    def get_count(cls):
        return cls.count

# @property - makes method act like attribute
class Circle:
    def __init__(self, radius):
        self._radius = radius
    
    @property
    def area(self):
        return 3.14 * self._radius ** 2

Common Use Cases

  • āœ… Timing function execution
  • āœ… Logging function calls
  • āœ… Caching results
  • āœ… Access control and validation
  • āœ… Retry logic
Example Code

Create a decorator that measures and prints function execution time.

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.4f} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "Done"

result = slow_function()
print(result)

Expected Output:

slow_function took [time] seconds
Done
Study Tips
  • •Read the theory content thoroughly before practicing
  • •Review the example code to understand key concepts
  • •Proceed to the Practice tab when you're ready to code