Syncing account progress…

Back

Advanced · 14 min

Decorators

Wrap a function to add behavior without changing its body.

Return a wrapper

A decorator receives a function and returns a replacement function. The wrapper can act before and after the original call.

def announce(function):
    def wrapper():
        print("Start")
        function()
    return wrapper

@announce
def work():
    print("Working")

work()

Output

Start
Working

Forward arguments

*args and **kwargs let a wrapper pass positional and keyword arguments to the wrapped function.

def double_result(function):
    def wrapper(*args, **kwargs):
        return function(*args, **kwargs) * 2
    return wrapper

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

print(add(2, 3))

Output

10

Decorators

  1. Read both decorators examples before answering.
  2. Run the task, compare its exact output, and revise the code if needed.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Normalize a result

Complete uppercase_result so the decorated greet function returns HELLO, ADA. Keep the supplied call.

Practice