Decorators the Modern Way: Wrapping a Function
When the hub needs the same cache in front of tomorrow's forecast as in front of today's weather, a decorator class per method multiplies again; a function that takes a function and returns a better one adds the feature to any call, and Python's @ and TypeScript's decorators are language shortcuts for that same move, applied where a function or class is defined.
Journeyman · OOP · Updated
After this lesson you can
- Write a function that takes a function and returns one with a feature added, and apply it with Python's @
- Explain how Python's @ decorators and TypeScript's decorators relate to the Decorator pattern, and how they differ
Key takeaways
- A function can take a function and return a new one that does a little more (remembers, logs) and then calls the original. That's a decorator for one call.
- One cached function works in front of any function of the same shape, so a new slow call needs no new class.
- Python's @cached above a def means the same as writing today = cached(today) after it.
- Python's @ and TypeScript's decorators wrap a definition once, for every caller; the Decorator pattern wraps one object at run time, so two objects can have different layers.
Before this: Decorator: Same Phone, More Features, and Functions as Values (passing a function, storing one, returning one).
The layers work. Then the wall panel gets a second line, tomorrow's forecast, and SkyCast's tomorrow call is as slow, and as counted, as today's. It needs the same cache. But CachedWeather from the last lesson is shaped around one method, today(). Caching tomorrow means a CachedTomorrow class, or a new interface, and the power company's hourly price, coming next month, means another. The feature is the same every time: ask once, remember the answer. Only the call it wraps is different. By the end of this lesson you'll have written that feature once, as a function that wraps a function, and seen what Python's and TypeScript's @ have to do with it.
The symptom: the same layer, once per method
Every decorator class from the last lesson has the same shape: a constructor that takes the thing to wrap, a field to hold it, and a method that does its bit and passes the call on. That's a lot of code around one idea, and it's tied to one interface. A cache for today() can't sit in front of tomorrow().
- The symptom: a decorator class for each method or interface, all doing the same job.
- The cause: the feature is written against a shape (the
WeatherSourceinterface), when all it needs is "a call that returns an answer".
What would you try?
Copy CachedWeather into CachedTomorrow. That's the class explosion from the last lesson, one level down.
Give CachedWeather an if for which method to call. Now the cache knows about every method it could ever wrap.
What we want is a cache that takes any call, wraps it, and hands back a call that does the same thing, remembered.
The fix: a function that wraps a function
In the last lesson's terms, each layer was an object that held a weather source. A function can do the same with a function: take one in, and hand back a new one that does its bit and then calls the original. A function that takes or returns a function is a higher-order function; one that wraps a function like this is often called a decorator too.
Func<string> today = Logged("today's weather", Cached(SkyCastToday));
Console.WriteLine("Wall panel: " + today());
Console.WriteLine("Phone app: " + today());
Func<string> tomorrow = Cached(SkyCastTomorrow);
Console.WriteLine("Tomorrow: " + tomorrow());
Console.WriteLine("Tomorrow: " + tomorrow());
string SkyCastToday()
{
Console.WriteLine("SkyCast: asked over the internet (about 2 seconds)");
return "72F, sunny";
}
string SkyCastTomorrow()
{
Console.WriteLine("SkyCast: asked over the internet (about 2 seconds)");
return "68F, rain";
}
// Takes any call that returns an answer, and hands back one that asks only once.
Func<string> Cached(Func<string> call)
{
string? saved = null;
return () => saved ??= call();
}
// Takes any call, and hands back one that writes a log line first.
Func<string> Logged(string label, Func<string> call)
{
return () =>
{
Console.WriteLine( quot;Log: asking for {label}");
return call();
};
}
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
SkyCast: asked over the internet (about 2 seconds)
Tomorrow: 68F, rain
Tomorrow: 68F, rain
String skyCastToday() {
IO.println("SkyCast: asked over the internet (about 2 seconds)");
return "72F, sunny";
}
String skyCastTomorrow() {
IO.println("SkyCast: asked over the internet (about 2 seconds)");
return "68F, rain";
}
// Takes any call that returns an answer, and hands back one that asks only once.
Supplier<String> cached(Supplier<String> call) {
String[] saved = { null };
return () -> {
if (saved[0] == null) saved[0] = call.get();
return saved[0];
};
}
// Takes any call, and hands back one that writes a log line first.
Supplier<String> logged(String label, Supplier<String> call) {
return () -> {
IO.println("Log: asking for " + label);
return call.get();
};
}
void main() {
Supplier<String> today = logged("today's weather", cached(this::skyCastToday));
IO.println("Wall panel: " + today.get());
IO.println("Phone app: " + today.get());
Supplier<String> tomorrow = cached(this::skyCastTomorrow);
IO.println("Tomorrow: " + tomorrow.get());
IO.println("Tomorrow: " + tomorrow.get());
}
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
SkyCast: asked over the internet (about 2 seconds)
Tomorrow: 68F, rain
Tomorrow: 68F, rain
def sky_cast_today():
print("SkyCast: asked over the internet (about 2 seconds)")
return "72F, sunny"
def sky_cast_tomorrow():
print("SkyCast: asked over the internet (about 2 seconds)")
return "68F, rain"
def cached(call):
"""Takes any call that returns an answer, and hands back one that asks only once."""
saved = None
def wrapper():
nonlocal saved
if saved is None:
saved = call()
return saved
return wrapper
def logged(label, call):
"""Takes any call, and hands back one that writes a log line first."""
def wrapper():
print(f"Log: asking for {label}")
return call()
return wrapper
today = logged("today's weather", cached(sky_cast_today))
print("Wall panel: " + today())
print("Phone app: " + today())
tomorrow = cached(sky_cast_tomorrow)
print("Tomorrow: " + tomorrow())
print("Tomorrow: " + tomorrow())
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
SkyCast: asked over the internet (about 2 seconds)
Tomorrow: 68F, rain
Tomorrow: 68F, rain
function skyCastToday() {
console.log("SkyCast: asked over the internet (about 2 seconds)");
return "72F, sunny";
}
function skyCastTomorrow() {
console.log("SkyCast: asked over the internet (about 2 seconds)");
return "68F, rain";
}
// Takes any call that returns an answer, and hands back one that asks only once.
function cached(call) {
let saved = null;
return () => (saved ??= call());
}
// Takes any call, and hands back one that writes a log line first.
function logged(label, call) {
return () => {
console.log(`Log: asking for ${label}`);
return call();
};
}
const today = logged("today's weather", cached(skyCastToday));
console.log("Wall panel: " + today());
console.log("Phone app: " + today());
const tomorrow = cached(skyCastTomorrow);
console.log("Tomorrow: " + tomorrow());
console.log("Tomorrow: " + tomorrow());
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
SkyCast: asked over the internet (about 2 seconds)
Tomorrow: 68F, rain
Tomorrow: 68F, rain
function skyCastToday(): string {
console.log("SkyCast: asked over the internet (about 2 seconds)");
return "72F, sunny";
}
function skyCastTomorrow(): string {
console.log("SkyCast: asked over the internet (about 2 seconds)");
return "68F, rain";
}
// Takes any call that returns an answer, and hands back one that asks only once.
function cached(call: () => string): () => string {
let saved: string | null = null;
return () => (saved ??= call());
}
// Takes any call, and hands back one that writes a log line first.
function logged(label: string, call: () => string): () => string {
return () => {
console.log(`Log: asking for ${label}`);
return call();
};
}
const today = logged("today's weather", cached(skyCastToday));
console.log("Wall panel: " + today());
console.log("Phone app: " + today());
const tomorrow = cached(skyCastTomorrow);
console.log("Tomorrow: " + tomorrow());
console.log("Tomorrow: " + tomorrow());
Log: asking for today's weather
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Log: asking for today's weather
Phone app: 72F, sunny
SkyCast: asked over the internet (about 2 seconds)
Tomorrow: 68F, rain
Tomorrow: 68F, rain
The first five lines are the last lesson's, line for line: the same layers, in the same order, with the log outside the cache. Then cached goes in front of tomorrow's call too, with no new class, and SkyCast is asked once for each day. The power company's price next month is one more cached(...).
cached remembers its answer in a variable the returned function can still see after cached has finished (that's called a closure). Each call to cached makes its own, so today's and tomorrow's answers never mix.
Where the languages differ. C# writes a call that takes nothing and returns a string as Func<string>, and Java as Supplier<String> (called with .get()). A Java lambda can't change a local variable, so saved is a one-slot array whose slot it can change. Python needs nonlocal saved to change the outer function's variable from inside wrapper. A real cached would work for any type of answer, not only strings; it's written for strings here to keep it short.
Python's `@`: the same thing, written above the function
Python has a shortcut for "replace this function with a wrapped one". Writing @cached on the line above a def means exactly the same as writing today = cached(today) right after it. Python's standard library also has one ready-made, functools.cache:
import functools
def cached(call):
saved = None
def wrapper():
nonlocal saved
if saved is None:
saved = call()
return saved
return wrapper
@cached
def today():
print("SkyCast: asked over the internet (about 2 seconds)")
return "72F, sunny"
@functools.cache
def tomorrow():
print("SkyCast: asked over the internet (about 2 seconds)")
return "68F, rain"
print("Wall panel: " + today())
print("Phone app: " + today())
print("Tomorrow: " + tomorrow())
print("Tomorrow: " + tomorrow())
SkyCast: asked over the internet (about 2 seconds)
Wall panel: 72F, sunny
Phone app: 72F, sunny
SkyCast: asked over the internet (about 2 seconds)
Tomorrow: 68F, rain
Tomorrow: 68F, rain
This sample is Python only, because @ above a function is Python's own syntax. functools.cache also remembers a separate answer for each different set of arguments, which is what you want for something like forecast("Monday").
TypeScript's decorators: the same move, for a class
TypeScript has an @ too, written above a class or one of its methods. A TypeScript decorator is a function that's handed the method and gives back a replacement, the same move as cached. Here a logged decorator wraps a class's today method:
function logged(method: () => string, context: ClassMethodDecoratorContext): () => string {
return function (this: unknown): string {
console.log(`Log: calling ${String(context.name)}`);
return method.call(this);
};
}
class SkyCast {
@logged
today(): string {
console.log("SkyCast: asked over the internet (about 2 seconds)");
return "72F, sunny";
}
}
It isn't run here: node can run TypeScript by removing its types, and a decorator isn't a type, so node can't remove it. Projects that use decorators (Angular and NestJS use them everywhere) compile with tsc first.
How they relate to the pattern
All three, the Decorator pattern, Python's @ and TypeScript's @, share one idea: wrap something, keep its shape, add a little. They differ in what they wrap, and when:
| The Decorator pattern | Python's @ |
TypeScript's @ |
|
|---|---|---|---|
| Wraps | one object | a function (or a class) | a class, or a method of one |
| When | while the program runs, whenever you build the layers | once, when the def runs |
once, when the class is defined |
| So | two objects of the same class can have different layers (one cached, one not) | every caller of that function gets the wrapper | every object of that class gets the wrapper |
So @cached above today is the decorator idea, applied to a function's definition. The Decorator pattern is the same idea applied to objects at run time, which is why the hub could give the wall panel a logged, cached SkyCast and a test a plain one.
Java and C# have @ and [...] too, but those are annotations and attributes: labels that don't wrap anything on their own. A framework reads the label and builds a wrapper for you, often a proxy. In the Spring framework, @Cacheable asks Spring to put a caching stand-in in front of the class:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
class WeatherService {
@Cacheable("weather")
public String today() {
return "72F, sunny";
}
}
Where you've already used it
- Python's
@functools.cache,@propertyand@staticmethod, and the@app.get("/rooms")above a FastAPI or Flask route. - In JavaScript, a "debounce" or "throttle" helper that takes an event handler and returns one that runs at most every so often.
- Angular's
@Componentand NestJS's@Controller, which are TypeScript decorators.
When not to use it
- When the feature needs more than the call. A cache that must forget after ten minutes, be cleared by a button, or report how often it hit is easier to read as an object with a name and methods: the last lesson's class.
- When the object has several methods to wrap together. One function wraps one call. To wrap a whole
WeatherSource, every method at once, the class decorator is the right tool. - When a stack of
@lines hides what runs. Three decorators above one function run in an order that's often misread (the one nearest thedefwraps first). Keep the stack short.
How often you'll meet it: every day in Python and TypeScript frameworks; now and then as a function you write (our estimate).
Check yourself
2 questions to try on the lesson page.
So what
A decorator doesn't have to be a class. When the feature wraps one call, write it once as a function that takes a function, and put it in front of any call that needs it; Python's and TypeScript's @ are that move, written where the function is defined.
Key terms
- Decorator Pattern
- Higher-Order Function
- Decorator
- Decorators in TypeScript