Adding an Audit Without Changing the Call
In this lesson, you port a Python decorator to a JavaScript wrapper that you apply by hand. The
translation desk wants an audit line for every quote, without changing how quote is called or what it
returns.
In Python, @with_audit(audit) decorates the quote method. Its inner function, wrapped, takes
*args and **kwargs, passes them on, appends a line, and returns the result. Because quote is a
method, self is the first argument, so the words are args[1]:
from functools import wraps
def with_audit(entries):
def decorate(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
result = fn(*args, **kwargs)
line = f"quoted {args[1]} words: {result}p"
entries.append(line)
return result
return wrapped
return decorate
audit = []
class Desk:
rate_pence = 12
@with_audit(audit)
def quote(self, words):
return words * self.rate_pence
desk = Desk()
print(desk.quote(400))
print(audit)
The @ line is shorthand for quote = with_audit(audit)(quote). In JavaScript, you write that
replacement out: pass the method to withAudit() with the audit array, and assign the result back to
desk.quote in place of the method. Unlike the @ line, it’s an ordinary assignment that runs after the
desk exists. The call stays the same: