Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • What @ Means in Python: Decorators Built by Hand, Then Shortened
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • SOLID in Python With Protocol and ABCs: Five Small Refactors of One Bloated Ticket Service
  • Strategy and Factory in Python: A dict Registry Instead of an if-elif Ladder
  • Adapter and Facade in Python: One Interface Over Three LLM Providers
  • Entities, Value Objects and Aggregates: One Root Guards the Rules, One Transaction Saves One Aggregate
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Object-Oriented Python

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

Does it always pass the call on? @auditedfunction, at definition close_ticket AuditedStoreobject, at runtime MemoryStore GuardedStoreobject, controls access MemoryStore always forwards, adds a log linealways forwards, adds a log linemay stop the call
The real line between a Decorator and a Proxy: does it always pass the call on?
Python decoratorDecorator patternProxy
WrapsA functionOne objectOne object
WhenOnce, at definition; every caller gets itAt runtime, per objectAt runtime, per object
JobAdd behaviourAdd behaviourControl access
Always passes the call on?Ours doesAlwaysNo

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.
  • @wraps keeps 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.

Keep going in Python · 30 of 57

Previous
Entities, Value Objects and Aggregates: One Root Guards the Rules, One Transaction Saves One Aggregate
Next post
Set Up a Python AI Project with uv, VS Code and an API Key in .env
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • A Python decorator
  • What functools.wraps does
  • The back door
  • One interface for the store
  • The Decorator pattern
  • The Proxy
  • Same shape, three jobs
  • How to say it in an interview
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.