StructuralPythonverifiedVerified

Proxy Pattern in Python

Provides a surrogate or placeholder for another object to control access, add lazy initialization, caching, logging, or access control.

How to Implement the Proxy Pattern in Python

1Step 1: Define the subject interface and real implementation

from typing import Protocol


class Subject(Protocol):
    def request(self) -> None: ...


class RealSubject:
    def request(self) -> None:
        print("RealSubject: handling request.")

2Step 2: Create the proxy with access control and logging

class ProxySubject:
    def __init__(self, real_subject: RealSubject) -> None:
        self._real_subject = real_subject

    def _check_access(self) -> bool:
        print("Proxy: checking access before forwarding request.")
        return True

    def _log_access(self) -> None:
        print("Proxy: logging time of request.")

    def request(self) -> None:
        if self._check_access():
            self._real_subject.request()
            self._log_access()

3Step 3: Access the real subject through the proxy

def client_code(subject: Subject) -> None:
    subject.request()


real = RealSubject()
client_code(real)

print("---")

proxy = ProxySubject(real)
client_code(proxy)

Proxy Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Proxy Pattern in the Real World

A corporate receptionist acts as a proxy for the CEO. When someone wants to meet the CEO, the receptionist checks credentials, schedules the meeting, and logs the visit before granting access. The visitor interacts with the receptionist using the same protocol they would use with the CEO—the receptionist simply adds control and record-keeping around that access.