Labs ICT
๐ŸŽ“ SIWES/IT Login

Decorators

1 min read | Python Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

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())

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))

๐Ÿงช Quick Quiz

What symbol is used for decorators in Python?