0Pricing
Python Academy · Lesson

Writing Custom Decorators

Create decorators using wrapper functions and functools.wraps.

Introduction

Decorators are functions that wrap other functions, adding behavior before or after without modifying the original.

What is a Decorator?

@decorator above a function is syntactic sugar for: func = decorator(func). The decorator receives the function and returns a wrapper.
def shout(func):
    def wrapper(*a, **kw):
        result = func(*a, **kw)
        return str(result).upper()
    return wrapper
@shout
def greet(name): return f'hello {name}'
print(greet('Alice'))

All lessons in this course

  1. Functions as First-Class Objects
  2. Writing Custom Decorators
  3. The @property Decorator
  4. @classmethod and @staticmethod
← Back to Python Academy