Proxy Pattern in Python
Proxy can add lazy loading, authorization, caching, or remote access without changing the real object.
What is Proxy Pattern?
Proxy can add lazy loading, authorization, caching, or remote access without changing the real object.
Control access to another object through a compatible stand-in.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
class Report:
# Proxy: stand in for another object and control access to it.
def display(self): return "Quarterly report"
class ReportProxy:
def __init__(self): self._report = None
def display(self):
# Delay construction until the object is actually needed.
if self._report is None:
print("Loading report")
self._report = Report()
return self._report.display()
proxy = ReportProxy()
print(proxy.display())
Expected output
Loading report
Quarterly report
How it works
ReportProxy creates the expensive report only when the client first asks to display it.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.