Labs ICT
โญ Pro Login

Decorators

Basic Decorator

A decorator is a function that wraps another function to extend its behavior. The @ syntax is syntactic sugar for func = decorator(func).

def shout(func):
    def wrapper():
        result = func()
        return result.upper()
    return wrapper

@shout
def greet():
    return "hello there"

print(greet())
Try it Yourself โ†’

Decorator with Arguments

If the wrapped function takes arguments, the wrapper must accept them too. Use *args and **kwargs to make it generic.

def logger(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args}")
        return func(*args, **kwargs)
    return wrapper

@logger
def add(a, b):
    return a + b

print(add(3, 7))
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What symbol is used for decorators in Python?