GCGrowCarrer

Decorators

Locked

Lesson 20 of 60 · Syntax · Challenging

Finish these first:Scope and Closures →Or pass the tests below to unlock it now.

1

The big idea

A decorator is a function that wraps another function: @deco is f = deco(f). Use functools.wraps to preserve metadata.

Think of it like this: Think of syntax and expressions like labeled measuring cups in a kitchen: each cup holds a specific kind of ingredient, and operators combine them into a new measurement.
Key words (tap to learn):
2

Read the lesson

A decorator is a function that wraps another function: @deco is f = deco(f). Use functools.wraps to preserve metadata.

import functools
def timed(fn):
    @functools.wraps(fn)
    def wrapper(*a, **kw):
        return fn(*a, **kw)
    return wrapper
3

Quick check

Before writing code: What should `(lambda f: (f(5), f(5)))(memoize(lambda x: x*2))` return when your implementation of Decorators is working?

4

Your challenge

2 sample tests, 1 hidden

Write decorator memoize(fn) that caches results by positional args.

Stuck? Get a hint (free)
More learning tools(compare languages, visual guide, related lessons)

Compare with another language

Similar to java.lambdas-functional-interfaces (30% overlap). No direct Java equivalent; closest are higher-order functions and annotations.

Visual walkthrough

A diagram, a step-by-step animation, and short captions for Decorators.

Mastery0%

Learn this first

Opens up next

This is the last lesson in this branch.