Tsallaka zuwa abun ciki
Justice Tech School

Decorators

A decorator is a function that takes a function and returns an improved one. Write @name above a def to apply it. Decorators are used for logging, timing, caching and permission checks. functools.wraps keeps the original name and docstring.

Example
import functools

def shout(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()
    return wrapper

@shout
def greet(name):
    return "hello " + name

print(greet("ada"))
print(greet.__name__)

Result

HELLO ADA
greet

Exercise

Apply the decorator.

shout
def hi():
    return "hi"

Quiz Test

What does a decorator take and return?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.