Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
An audit log for closing Help Desk tickets, built three ways. An @audited function decorator fixed at definition time (with a __wrapped__ back door), an AuditedStore that wraps one object at runtime, and a GuardedStore proxy that never reaches the real store for an agent.
What you will learn
- Write a function decorator with functools.wraps and say when it runs
- Find the __wrapped__ back door that skips a decorator
- Wrap one object at runtime with the Decorator pattern
- Use a Proxy to control access, and tell it apart from a Decorator
Before you start
- Python functions as objects
- SOLID in Python With Protocol and ABCs
Three things sound alike and get mixed up all the time: a Python decorator, the Decorator pattern, and a Proxy. All three wrap something and pass the call along, so they even look alike in code. We'll build one audit log for a Help Desk three ways and see what makes each one different.
The use case: a support agent closes ticket 101, and every time that happens we want a line in the audit log. We want it without touching the close code itself. From the outside, all three wrappers look the same: a call goes in, a call comes out. So the question isn't how they look. It's when they wrap, and what they're for.
A Python decorator
audit_func.py:
from functools import wraps
LOG = []
def audited(fn):
@wraps(fn)
def wrapper(*args):
result = fn(*args)
call = ", ".join(map(str, args))
LOG.append(f"AUDIT {fn.__name__}({call})")
return result
return wrapper
@audited
def close_ticket(ticket_id):
"""Mark a ticket as closed."""
return f"T-{ticket_id} closed"
if __name__ == "__main__":
print(close_ticket(101))
print(LOG)
T-101 closed
['AUDIT close_ticket(101)']
The @audited line runs once, when Python defines the function. It passes close_ticket into audited, and the name close_ticket now points to the wrapper. When you call it, the wrapper runs first, calls the original inside, and adds a log line when the result comes back.
The @ sign is just a short way to write close_ticket = audited(close_ticket), and it happens once, at definition time.
What functools.wraps does
wraps_check.py compares a wrapper without @wraps and one with it:
from functools import wraps
def plain(fn):
def wrapper(*args):
return fn(*args)
return wrapper
def kept(fn):
@wraps(fn)
def wrapper(*args):
return fn(*args)
return wrapper
def close_ticket(ticket_id):
"""Mark a ticket as closed."""
return f"T-{ticket_id} closed"
a = plain(close_ticket)
b = kept(close_ticket)
print(a.__name__, "|", a.__doc__)
print(b.__name__, "|", b.__doc__)
print(b.__wrapped__ is close_ticket)
wrapper | None
close_ticket | Mark a ticket as closed.
True
Without @wraps, the name is wrapper and the docstring is gone. With it, the name and the docstring are back, so help pages and docs tools see close_ticket as if nothing was wrapped. wraps also stores the original function on the wrapper as __wrapped__, and the check prints True.
The back door
That __wrapped__ has a side effect. back_door.py:
from audit_func import LOG, close_ticket
LOG.clear()
close_ticket(102)
close_ticket.__wrapped__(103)
print(LOG)
['AUDIT close_ticket(102)']
Two calls, one audit line. The call to __wrapped__ went straight to the original function, around the wrapper, so ticket 103 was closed and nothing was logged. A decorator is great for logging and timing. But if the audit must never be skipped, a decorator on its own isn't enough.
One interface for the store
For the next two we wrap an object, not a function. store.py defines the contract:
from typing import Protocol
class TicketStore(Protocol):
def close(self, ticket_id: int) -> str: ...
class MemoryStore:
def close(self, ticket_id: int) -> str:
return f"T-{ticket_id} closed"
Anything that wraps the store has to offer the same close method.
The Decorator pattern
audit_pattern.py:
from store import MemoryStore, TicketStore
class AuditedStore:
def __init__(self, inner: TicketStore, log):
self.inner = inner
self.log = log
def close(self, ticket_id: int) -> str:
result = self.inner.close(ticket_id)
self.log.append(f"AUDIT close({ticket_id})")
return result
def build(audit: bool, log) -> TicketStore:
store = MemoryStore()
if audit:
return AuditedStore(store, log)
return store
log = []
print(build(True, log).close(101))
print(build(False, log).close(102))
print(log)
T-101 closed
T-102 closed
['AUDIT close(101)']
AuditedStore keeps another store as self.inner. From outside both have the same close. It passes the call on, gets the result, adds its own job (one audit line) and returns the result.
The big difference from the @ sign is in build: it wraps the store only when audit is True. Closing 101 goes through AuditedStore and is logged; closing 102 uses a bare MemoryStore and isn't. The Decorator pattern is chosen at runtime, one object at a time. A Python decorator is fixed for every caller the moment the function is defined.
The Proxy
audit_proxy.py:
from store import MemoryStore, TicketStore
class GuardedStore:
def __init__(self, inner: TicketStore, role):
self.inner = inner
self.role = role
self.calls = 0
def close(self, ticket_id: int) -> str:
if self.role != "lead":
return f"denied for {self.role}"
self.calls += 1
return self.inner.close(ticket_id)
agent = GuardedStore(MemoryStore(), "agent")
lead = GuardedStore(MemoryStore(), "lead")
print(agent.close(101), agent.calls)
print(lead.close(101), lead.calls)
denied for agent 0
T-101 closed 1
Almost the same class: an inner store and the same close. But it checks the role first. For the agent, the counter stays at 0: the real store was never reached. The lead gets through, and the counter goes to 1. A Proxy stands in front of the real object and decides whether the call happens, like a permission check, a cache, or a lazy connection.
Same shape, three jobs
| Python decorator | Decorator pattern | Proxy | |
|---|---|---|---|
| Wraps | A function | One object | One object |
| When | Once, at definition; every caller gets it | At runtime, per object | At runtime, per object |
| Job | Add behaviour | Add behaviour | Control access |
| Always passes the call on? | Ours does | Always | No |
When you're not sure which one you're looking at, ask two questions: when does it wrap, and does it always pass the call on?
How to say it in an interview
"Is a Python decorator the same as the Decorator pattern?" Start with the level: same idea, but the @ sign wraps a function at definition time and the pattern wraps an object at runtime. Then name the job: if the wrapper adds something and always forwards, it's a Decorator; if it can block or delay the call, it's a Proxy. Mention that wraps keeps the name while __wrapped__ is a way around it, and you'll stand out.
A fourth wrapper, the Adapter, changes the interface instead of keeping it. That's next in Adapter and Facade over three LLM providers.
Recap
- A Python decorator wraps a function once, when it's defined.
@wrapskeeps the name and the docstring, and__wrapped__can skip the wrapper.- The Decorator pattern wraps an object at runtime and adds a job.
- A Proxy controls access to the real object.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
