Composite Proxy
Composite + Proxy (GoF Structural)
Composite: "Compose objects into tree structures to represent part-whole hierarchies." Proxy: "Provide a surrogate or placeholder for another object to control access to it." — GoF
What they share
Both patterns have the same interface as the "real" object. The caller does not see the difference between:
- one object and a group of them (Composite),
- the real object and a wrapper (Proxy).
This is the strength of structural patterns: same API, interchangeable.
Composite
Canonical form
from typing import Protocol
class FileSystemNode(Protocol):
"""Shared interface for leaf and composite."""
name: str
def size(self) -> int: ...
class File: # ← LEAF
def __init__(self, name: str, size_bytes: int):
self.name = name
self._size = size_bytes
def size(self) -> int:
return self._size
class Directory: # ← COMPOSITE
def __init__(self, name: str):
self.name = name
self._children: list[FileSystemNode] = []
def add(self, node: FileSystemNode) -> None:
self._children.append(node)
def size(self) -> int:
return sum(child.size() for child in self._children)
# ↑ call .size() on every child, no matter what it is
Tree usage:
project = Directory("project")
project.add(File("README.md", 1024))
src = Directory("src")
src.add(File("main.py", 4096))
src.add(File("utils.py", 2048))
project.add(src) # ← Directory inside Directory!
print(project.size()) # 7168 — recursive
Key signs of Composite:
- A shared interface (
FileSystemNode) for leaf (File) and composite (Directory). - The composite contains children of the same type —
list[FileSystemNode]. - The composite delegates operations to children —
sum(child.size() for child in children). - Recursion is natural — Directory inside Directory just works.
Classic Composite examples
| Domain | Leaf | Composite |
|---|---|---|
| File system | File |
Directory |
| UI | Button, Label |
Panel, Form |
| AST | Literal, Variable |
BinaryExpr, IfStatement |
| Org chart | Employee |
Manager (has reports) |
| Documents | Paragraph |
Section, Chapter |
| Notifications | EmailNotifier |
MultiNotifier |
| Geometric | Point, Line |
Group of shapes |
Pythonic details
add / remove lives on the Composite, not the Protocol
Classic GoF offers "Transparent Composite" — add() in the Protocol with a no-op in the leaf. That is an anti-pattern, it breaks LSP:
class FileSystemNode(Protocol):
def size(self) -> int: ...
def add(self, node) -> None: ... # ❌ meaningless for File!
File.add(node) is nonsense. Use "Safe Composite" instead: add only on the composite. The caller knows the type when adding:
class FileSystemNode(Protocol):
def size(self) -> int: ...
# no add!
class Directory:
def add(self, node: FileSystemNode) -> None: # only here
...
The caller cannot accidentally call file.add(...) — File does not have it. LSP holds.
Pythonic iteration via __iter__
For tree traversal, implement __iter__ on the composite:
class Directory:
def __iter__(self):
for child in self._children:
yield child
if isinstance(child, Directory):
yield from child # recursive
Then for node in directory: walks the whole tree like a standard container.
When to use Composite
- A tree structure with part-whole semantics (
size,count,flatten). - One API for the whole tree — the caller should not have to distinguish leaf and node.
- Recursive operations at every level.
When NOT to use it
- Leaf and composite have fundamentally different methods — that is not Composite, it is just a naming collision.
- A tree with a fixed depth of 2 — separate types are simpler.
- The "composite" is really a collection — a plain
listis enough.
Proxy
Canonical form
from typing import Protocol
class ImageLoader(Protocol):
def get_data(self) -> bytes: ...
def get_size(self) -> tuple[int, int]: ...
class RealImage: # ← expensive object
def __init__(self, path: str):
self._path = path
self._data = self._load_from_disk() # ← expensive! file read
print(f"loaded {path}")
def _load_from_disk(self) -> bytes:
# real read
return b"...binary..."
def get_data(self) -> bytes:
return self._data
def get_size(self) -> tuple[int, int]:
return (1920, 1080)
class LazyImageProxy: # ← Proxy
"""Loads the real RealImage on the first call only."""
def __init__(self, path: str):
self._path = path
self._real: RealImage | None = None # ← None until needed
def _ensure_loaded(self) -> RealImage:
if self._real is None:
self._real = RealImage(self._path) # ← only here!
return self._real
def get_data(self) -> bytes:
return self._ensure_loaded().get_data()
def get_size(self) -> tuple[int, int]:
return self._ensure_loaded().get_size()
Usage:
proxy = LazyImageProxy("huge_photo.jpg") # 0 seconds, nothing loaded
# ... user scrolls past the image without viewing it ...
# RealImage is NOT created
# Only when really needed:
data = proxy.get_data() # RealImage is created here
Key signs of Proxy:
- The same interface as the real object.
- Creates or accesses the real object on demand.
- Extra logic: access control, cache, lazy init, remote calls.
Four kinds of Proxy
1. Virtual Proxy (lazy)
"An expensive object is created only when needed". The LazyImageProxy above.
2. Protection Proxy (security)
Checks permissions:
class AdminOnlyResource:
def __init__(self, real: Resource, current_user: User):
self._real = real
self._user = current_user
def delete(self):
if not self._user.is_admin:
raise PermissionError("admin only")
self._real.delete()
def read(self):
return self._real.read() # delegate without checks
3. Caching Proxy
Caches expensive operations:
class CachingApiClient:
def __init__(self, real: ApiClient):
self._real = real
self._cache: dict[str, dict] = {}
def get(self, url: str) -> dict:
if url not in self._cache:
self._cache[url] = self._real.get(url)
return self._cache[url]
4. Remote Proxy
Looks like a local object, actually makes a network call:
class RemoteUserService:
def __init__(self, http_client, url):
self._http = http_client
self._url = url
def get_user(self, user_id: int) -> User:
response = self._http.get(f"{self._url}/users/{user_id}")
return User(**response.json())
(Classic RPC stubs, gRPC client classes — all Remote Proxies.)
Proxy vs Decorator vs Adapter
All three are wrappers with the same or a new interface. The difference is intent:
| Aspect | Decorator | Proxy | Adapter |
|---|---|---|---|
| Goal | Add behaviour | Control access | Make compatible |
| Interface | Same | Same | New |
| Stack of several | Yes, usually | Rarely | Not natural |
| Caller knows? | Usually yes | Often no (transparent) | Yes |
| Examples | Logging, Retry, RateLimiting | LazyLoad, Caching, Security, Remote | LegacyAPIWrapper |
Subtle point: one class can be both Proxy and Decorator. The distinction is not formal, it is semantic. "Why did you create this?"
- "To add retry" → Decorator.
- "To lazy-load" → Proxy.
When to use Proxy
- Expensive objects — lazy loading.
- Caching results from external calls.
- Access control — permission check before delegation.
- Remote calls — a local stand-in for a distant object.
- Reference counting / smart pointers (rare in Python because of GC).
When NOT to use it
- A simple wrapper class that adds nothing extra — remove it.
@cacheon a function is enough instead of a caching proxy.- The object is already cheap — a lazy proxy is not justified.
Pythonic alternatives to Proxy
@cached_property instead of a Virtual Proxy for a single field
from functools import cached_property
class Image:
def __init__(self, path: str):
self._path = path
@cached_property
def data(self) -> bytes: # computed once
return self._load_from_disk()
This makes one field lazy. For the whole object, you still need a Proxy.
functools.cache instead of a Caching Proxy
@cache
def get_user(user_id: int) -> User:
return _real_get_user(user_id)
If the cache logic is simple (one function), @cache is enough. For a stateful cache (with expiration, eviction), use a full Caching Proxy.
__getattr__ for a transparent Proxy
class LazyProxy:
def __init__(self, factory):
self._factory = factory
self._real = None
def __getattr__(self, name): # ← catches ANY attribute access
if self._real is None:
self._real = self._factory()
return getattr(self._real, name)
This way you can wrap any object without implementing each method by hand. Magical, but harder for static type checking.
Anti-patterns
Composite
1. Transparent Composite (LSP failure)
class FileSystemNode(Protocol):
def add(self, node): ... # ← also for File?
class File:
def add(self, node): raise NotImplementedError # ← LSP!
Use Safe Composite instead: add only on Directory.
2. Composite that shares state with the leaf
class Directory:
_shared_metadata = {} # ← class-level
All directories share metadata? Usually not what you wanted.
Proxy
3. A Proxy that does nothing
class UselessProxy:
def __init__(self, real):
self._real = real
def do(self, x):
return self._real.do(x) # just forwards
Remove it. The caller can hold the real reference directly.
4. Caching Proxy with no invalidation
class CachingProxy:
def get(self, key):
if key not in self._cache:
self._cache[key] = self._real.get(key)
return self._cache[key] # ← when do we clear it?
The cache is never cleared — stale data forever. Every Caching Proxy needs an invalidation strategy (TTL, LRU, manual invalidate).
Composite + Proxy together
Often used together: a tree where each node is a Proxy that lazily loads its children.
class LazyDirectory: # Composite + Proxy
def __init__(self, name: str, loader):
self.name = name
self._loader = loader
self._children: list[FileSystemNode] | None = None
def _children_loaded(self) -> list[FileSystemNode]:
if self._children is None:
self._children = self._loader() # ← lazy load
return self._children
def size(self) -> int:
return sum(c.size() for c in self._children_loaded())
This is Composite (aggregates children) + Proxy (lazy load). A standard pattern for UI with big trees (a file explorer, for example).
Rules of thumb
- Composite is for tree structures with part-whole operations (size, count, depth, flatten).
- Leaf and composite share the same interface, with different implementations.
add/removeonly on the composite (Safe Composite, not Transparent).- Proxy is for access control, not for adding behaviour (that is Decorator).
- Decorator vs Proxy is a semantic distinction. Formally they are nearly identical.
@cached_propertyreplaces a Virtual Proxy for a single field.@cachereplaces a Caching Proxy for a stateless cache.- A Caching Proxy needs an invalidation plan. Otherwise it is a bug.
One-line summary
Composite is a tree where leaf and node are interchangeable through a shared interface. Proxy is a transparent intermediary with the same interface that controls access (lazy, security, cache, remote). Both are structurally similar, conceptually different.