Making Existing Code Fit: The Adapter Pattern in Python
This article explains how the Adapter pattern lets existing code serve a new interface by converting calls, data and errors, how functions are adapted with cmp_to_key, and why blind forwarding leaks the interface it should hide.
Programs regularly need code that they did not write and cannot change, such as a third-party library, a legacy module or a service client, and that code rarely offers the interface that the rest of the program expects. Editing every caller to accommodate it spreads the foreign interface throughout the program, while editing the foreign code is often impossible. The present article examines the Adapter pattern, which places a small object between the two, so that the client keeps its interface and the existing code keeps its own. It builds an adapter that converts calls, data and errors, shows that functions can be adapted as well as objects, compares object adapters with class adapters and with related patterns, and analyses the errors that make an adapter leak the interface it was meant to hide. Letting existing code serve a new interface without modifying either side is the secret weapon of the Adapter pattern.
Converting Calls, Data and Errors
Many games allow a player to connect an older controller and remap its buttons, so that the game keeps asking for "jump" and "attack" while a configuration layer decides which physical button produces each action. This means that an adapter implements the interface that the client expects, the target, and translates each call into the operations of the existing object, the adaptee. The analogy, however, stops at this point, because remapping only changes which button triggers an action, whereas a useful adapter usually also converts formats, units and errors. In the following example, the program expects sensors with a read_celsius method, declared as a typing.Protocol as described in the article devoted to advanced type hints, while a legacy thermometer returns strings such as "F:70.7" in degrees Fahrenheit.
from typing import Protocol
class TemperatureSensor(Protocol):
def read_celsius(self) -> float: ...
class ModernSensor:
def read_celsius(self):
return 21.5
class LegacyThermometer:
def __init__(self, raw):
self.raw = raw
def get_reading(self):
return self.raw
class SensorError(Exception):
pass
class ThermometerAdapter:
def __init__(self, thermometer):
self._thermometer = thermometer
def read_celsius(self):
raw = self._thermometer.get_reading()
unit, _, value = raw.partition(":")
if unit != "F":
raise SensorError(f"unexpected reading {raw!r}")
return round((float(value) - 32) * 5 / 9, 1)
def report(sensor: TemperatureSensor):
return f"{sensor.read_celsius():.1f} C"
for sensor in (ModernSensor(), ThermometerAdapter(LegacyThermometer("F:70.7"))):
print(report(sensor))
# Output: 21.5 C
# Output: 21.5 C
try:
ThermometerAdapter(LegacyThermometer("ERR")).read_celsius()
except SensorError as error:
print(error) # Output: unexpected reading 'ERR'
The function report treats both sensors identically and never learns that one of them speaks another format. The adapter performs three conversions: it renames the call, it converts the string in Fahrenheit into a number in Celsius, and it translates a malformed reading into the error type that the program already handles. Neither the legacy class nor the client was modified.
Adapting Functions
In Python, an adapter does not have to be a class, because functions are objects with an interface of their own: their parameters and their return value. The standard library contains a clear example, functools.cmp_to_key, which converts an old-style comparison function, one that returns a negative number, zero or a positive number, into the key function that sorted expects. It was added in Python 2.7 and 3.2 as a transition tool for code written for the cmp argument of Python 2, which Python 3 no longer accepts.
from functools import cmp_to_key
def compare_versions(a, b):
left = [int(part) for part in a.split(".")]
right = [int(part) for part in b.split(".")]
return (left > right) - (left < right)
versions = ["3.10.1", "3.9.18", "3.14.3"]
print(sorted(versions)) # Output: ['3.10.1', '3.14.3', '3.9.18']
print(sorted(versions, key=cmp_to_key(compare_versions))) # Output: ['3.9.18', '3.10.1', '3.14.3']
The plain sort compares the strings character by character and places 3.10 before 3.9, while the adapted comparison orders the versions numerically. When the comparison function does not already exist, a key function that returns the tuple of integers is simpler and faster, since it is computed once per element instead of once per comparison; the adapter is the right tool when the comparison is given and cannot be rewritten.
Object Adapters, Class Adapters and Related Patterns
This section distinguishes the two forms of the pattern and the patterns that resemble it. An object adapter holds the adaptee as an attribute, as in the examples above, and can therefore adapt any object with the right methods, including subclasses and instances created elsewhere. A class adapter inherits from both the target and the adaptee, which Python allows through multiple inheritance, but it binds the adapter to one concrete class and exposes every public method of that class. Related patterns share the structure of a wrapper but differ in intent: a proxy keeps the same interface and controls access to the object, a facade defines a new and simpler interface over several objects, and a bridge, as described in the article devoted to the Bridge pattern, separates two hierarchies by design, whereas an adapter reconciles interfaces that already exist.
Pitfalls of the Adapter Pattern
An adapter is valuable because it confines a foreign interface to one place, so its errors are those that let that interface escape or that hide what the conversion costs. Six pitfalls are distinguished, which are the following:
- Forwarding everything. An adapter that forwards every unknown attribute with
__getattr__exposes the whole interface of the adaptee, so clients start depending on it. - Missing special methods. Python looks up special methods such as
__len__on the type, so__getattr__never supplies them, as described in the article devoted to proxy objects. - Leaking foreign errors. An adapter that lets the exceptions of the adaptee pass unchanged forces callers to handle errors from a library that they do not know about.
- Hidden costs. A conversion that looks like a simple attribute access may perform parsing, copying or network calls on every call.
- Chains of adapters. An adapter of an adapter of an adapter is usually a sign that one of the interfaces should change.
- Adapting what could be changed. When the code is owned by the same team, changing the interface directly is simpler than maintaining an adapter.
The first two pitfalls are reproduced in the following example, with an adapter that forwards blindly and one that implements exactly the interface that clients expect.
class LegacyQueue:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def count(self):
return len(self._items)
class LeakyAdapter:
def __init__(self, legacy):
self._legacy = legacy
def __getattr__(self, name):
return getattr(self._legacy, name)
class QueueAdapter:
def __init__(self, legacy):
self._legacy = legacy
def append(self, item):
self._legacy.push(item)
def __len__(self):
return self._legacy.count()
leaky = LeakyAdapter(LegacyQueue())
leaky.push("job")
try:
len(leaky)
except TypeError as error:
print(error) # Output: object of type 'LeakyAdapter' has no len()
adapted = QueueAdapter(LegacyQueue())
adapted.append("job")
print(len(adapted), hasattr(adapted, "push")) # Output: 1 False
The leaky adapter lets its clients call push, the legacy method that the adapter was meant to hide, and still fails on len. The explicit adapter offers only append and len, the interface of a Python sequence that clients already know, and its clients no longer depend on the legacy queue at all.
Choosing Whether to Adapt
Consequently, an adapter fits when an interface must be reconciled with code that cannot change, and other tools fit when that condition does not hold, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Third-party or legacy code with the wrong interface | An object adapter |
| A function with the wrong signature or return value | A wrapper function, functools.partial or a ready-made adapter such as cmp_to_key |
| Code owned by the same team | Changing the interface directly |
| Several objects used together through one entry point | A facade |
| The same interface with access control or laziness | A proxy |
| Two dimensions of variation planned in advance | A bridge |
Conclusion
It is concluded that the Adapter pattern lets existing code serve an interface that it was not written for, by converting calls, data and errors in one small object or function, and that Python supports both object and class adapters, as well as function adapters such as functools.cmp_to_key. This magic depends on implementing the target interface explicitly, special methods included, instead of forwarding everything, and on keeping the foreign errors and costs inside the adapter. Creating new objects by copying a fully configured instance, instead of building each one from its constructor, is the purpose of the Prototype pattern, which is developed in a future article of this series.