Lesson 2 · Unit 03
Decorator and proxy
Add behaviour by wrapping, not by editing
What you practise
- Add logging, caching or retries by wrapping, without touching the wrapped code
- Higher-order functions
- The order wrappers apply in
Try a question from this lesson
Pick one
Two wrappers are stacked. What does this print?
def twice(fn):
return lambda s: fn(s) * 2
def star(fn):
return lambda s: fn(s) + "*"
def name(s):
return s
f = twice(star(name))
print(f("a"))function twice(fn) {
return (s) => fn(s).repeat(2);
}
function star(fn) {
return (s) => fn(s) + "*";
}
function name(s) {
return s;
}
const f = twice(star(name));
console.log(f("a"));type Fn = (s: string) => string;
function twice(fn: Fn): Fn {
return (s) => fn(s).repeat(2);
}
function star(fn: Fn): Fn {
return (s) => fn(s) + "*";
}
function name(s: string): string {
return s;
}
const f = twice(star(name));
console.log(f("a"));Hint
Work from the inside out: what does the inner wrapped function return for "a"?
Correct answer
a*a*
Why
The star wrapper is innermost, so it produces "a*" first. The outer wrapper then doubles that whole result. Stacked the other way round, the answer would be "aa*".
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Decorator
A decorator wraps something and offers the same interface, with extra behaviour before or after the real call: logging, caching, timing, retrying.
Callers use the wrapped version exactly as they used the original. In these languages the lightest decorator is a function that takes a function and returns a new one.
Python noteWriting @shout on the line above def greet is shorthand for greet = shout(greet): the name now refers to the wrapped version.
Concept
Wrappers stack
Each wrapper only knows the thing directly inside it. In a(b(f)), the call enters through a, passes through b, reaches f, and the result travels back out the same way.
So the outermost wrapper sees every call, and an inner wrapper sees only what the outer ones let through.
Python noteStacked @a then @b above a function means a(b(f)): the decorator nearest the def is applied first.
8 more exercises in the app
- 3× type the answer
- 1× order the lines
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
- 1× multiple choice
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.