A pass-through proxy is boring. The point of a proxy is to add behavior without changing the interface. The classic addition is a cache: remember each key's result so a repeat request skips the expensive service entirely.
Give the proxy a dictionary. On fetch, if the key is already cached, return the stored value and do not touch the real service. Otherwise call the service once, store the result, and return it.
The tell-tale sign it works: fetching the same key twice leaves the service's call counter at 1.
class RealService:
def __init__(self, backend):
self.backend = dict(backend)
self.calls = 0
def fetch(self, key):
self.calls += 1
return self.backend.get(key)
class Proxy:
def __init__(self, real):
self.real = real
self._cache = {}
def fetch(self, key):
"""Return the cached value if present, else fetch once and cache it."""
# Step 1 behavior: delegate to the real service.
# TODO: check self._cache first; only call the service on a miss, then store the result.
return self.real.fetch(key)
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
A pass-through proxy is boring. The point of a proxy is to add behavior without changing the interface. The classic addition is a cache: remember each key's result so a repeat request skips the expensive service entirely.
Give the proxy a dictionary. On fetch, if the key is already cached, return the stored value and do not touch the real service. Otherwise call the service once, store the result, and return it.
The tell-tale sign it works: fetching the same key twice leaves the service's call counter at 1.
Press Run Tests or ββ© to check your solution.