A Simple Front for a Complex Subsystem: The Facade Pattern in Python
This article explains how the Facade pattern gives a subsystem a single, simpler interface, how it can undo partial work, which standard-library functions already act as facades, and how it differs from Adapter and Mediator.
A task that involves several subsystems, each with its own classes, methods and required order of calls, forces every client that performs it to learn all of them and to repeat the same sequence, with the same opportunities for error, wherever the task appears. The present article examines the Facade pattern, which places a single, higher-level interface in front of such a subsystem, so that the common path becomes one call while the individual parts remain available. It builds a facade over three cooperating classes, shows how the facade can undo its own work when a step fails, identifies the facades that the Python standard library already offers, and distinguishes the pattern from the Adapter and the Mediator. Reducing a sequence that many clients repeat to one well-named operation, without taking the detailed controls away, is the secret weapon of the Facade pattern.
One Entry Point for Several Subsystems
Many games offer an automatic equipment button in the inventory screen, which chooses and equips the best item for every slot in one press, while each slot can still be changed by hand. A facade provides the same service to code: it offers one operation that coordinates several subsystems in the right order, and the subsystems keep their own interfaces for the clients that need finer control. The analogy, however, stops at this point, because the button acts on a single inventory, whereas a facade coordinates independent objects, each of which can fail on its own, a difference that the next sections address.
class Lights:
def dim(self, level):
print(f"lights at {level}%")
def restore(self):
print("lights at 100%")
class Projector:
def on(self):
print("projector on")
def select_input(self, source):
print(f"projector input: {source}")
def off(self):
print("projector off")
class Player:
def play(self, title):
print(f"playing {title!r}")
def stop(self):
print("player stopped")
class HomeTheater:
def __init__(self, lights=None, projector=None, player=None):
self.lights = Lights() if lights is None else lights
self.projector = Projector() if projector is None else projector
self.player = Player() if player is None else player
def watch(self, title):
self.lights.dim(20)
self.projector.on()
self.projector.select_input("player")
self.player.play(title)
def end(self):
self.player.stop()
self.projector.off()
self.lights.restore()
theater = HomeTheater()
theater.watch("Metropolis")
# Output: lights at 20%
# Output: projector on
# Output: projector input: player
# Output: playing 'Metropolis'
theater.end()
# Output: player stopped
# Output: projector off
# Output: lights at 100%
The client knows two operations, watch and end, instead of three classes and seven methods, and the order of the steps is written once, inside the facade. The subsystems are received as parameters with default values, as described in the article devoted to dependency injection, so a test can pass fakes and a different projector can be installed without editing the facade. A client that needs a brightness of 50 percent still calls theater.lights.dim(50) directly, because a facade simplifies the common path without forbidding the others.
Facades in the Standard Library
Python applies the pattern in several modules that most programs already use. The documentation of subprocess recommends run() for every case that it can handle and keeps the underlying Popen class for advanced uses, so run is a facade over process creation, communication and waiting. In the same way, json.dumps builds a JSONEncoder with the given options and calls its encode method, and it reuses a cached encoder when no option is given, as the source of CPython shows. The following example verifies that both paths produce the same result.
import json
data = {"b": 1, "a": [1, 2]}
print(json.dumps(data, sort_keys=True)) # Output: {"a": [1, 2], "b": 1}
print(json.JSONEncoder(sort_keys=True).encode(data)) # Output: {"a": [1, 2], "b": 1}
Most programs only need the function, while a program that must stream a large document can call JSONEncoder.iterencode directly. A package can act as a facade as well: its __init__.py imports the few names that clients should use, and the modules that implement them remain importable for the clients that need more.
Facade, Adapter and Mediator
This section distinguishes the Facade pattern from two patterns with which it is often confused. An adapter converts the interface of one existing class into the interface that a client expects, as described in the article devoted to the Bridge pattern, whereas a facade defines a new and simpler interface over many classes. A mediator also coordinates several objects, but those objects know the mediator and communicate through it; the subsystems behind a facade do not know that the facade exists and keep working without it.
Pitfalls of the Facade Pattern
A facade concentrates the knowledge of a whole subsystem in one place, so its errors usually come from concentrating too much or from hiding too little. Six pitfalls are distinguished, which are the following:
- Partial failure. A sequence that fails halfway leaves the subsystem in an intermediate state, such as dimmed lights with the projector off, unless the facade undoes the steps already completed.
- The god object. A facade that gathers every operation of every subsystem becomes the most coupled class of the program; several small facades, one per task, are easier to maintain.
- Hard-wired subsystems. A facade that creates its subsystems inside its methods cannot be tested with fakes or reconfigured without editing it.
- Leaking subsystem types. A facade whose methods return or require the internal classes of the subsystem forces its clients to learn them anyway.
- Forbidding direct access. Hiding the subsystem completely forces every advanced case to extend the facade, which then grows into the god object.
- Pass-through layers. A facade method that forwards one call to one method adds a name without removing any complexity.
The first pitfall is reproduced in the following example, in which the projector fails to start. The naive facade leaves the lights dimmed, while the facade that runs the session as a context manager, built with contextlib.contextmanager as described in the article devoted to custom context managers, restores them before the error propagates.
from contextlib import contextmanager
class Lights:
def __init__(self):
self.level = 100
def dim(self, level):
self.level = level
def restore(self):
self.level = 100
class BrokenProjector:
def on(self):
raise OSError("lamp failure")
def off(self):
pass
class NaiveTheater:
def __init__(self, lights, projector):
self.lights, self.projector = lights, projector
def watch(self):
self.lights.dim(20)
self.projector.on()
class SafeTheater(NaiveTheater):
@contextmanager
def session(self):
self.lights.dim(20)
try:
self.projector.on()
try:
yield self
finally:
self.projector.off()
finally:
self.lights.restore()
naive_lights, safe_lights = Lights(), Lights()
try:
NaiveTheater(naive_lights, BrokenProjector()).watch()
except OSError:
pass
try:
with SafeTheater(safe_lights, BrokenProjector()).session():
pass
except OSError as error:
print(error) # Output: lamp failure
print(naive_lights.level, safe_lights.level) # Output: 20 100
Both facades let the error reach the client, which must still learn that the projector failed, but only the second one leaves the subsystem as it found it. Each finally clause undoes exactly the steps that completed before the failure, in reverse order.
Choosing Whether to Add a Facade
Consequently, a facade is justified when several clients repeat the same coordinated sequence, and not when it would merely rename existing calls, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Several clients repeat the same sequence of calls | A facade with one method per task |
| The sequence must be undone if a step fails | A facade method written as a context manager |
| One existing class has the wrong interface | An adapter |
| Objects must coordinate with one another | A mediator |
| A package exposes many internal modules | A package __init__.py that imports the public names |
| A facade method would forward a single call | Calling the subsystem directly |
Conclusion
It is concluded that the Facade pattern gives the common use of a subsystem a single, simple interface, which records the order of the steps in one place, while the subsystem remains available for the cases that require finer control, and that Python already follows this design in subprocess.run and json.dumps. This magic depends on receiving the subsystems instead of creating them, on undoing completed steps when one fails and on keeping each facade small. Treating a whole tree of objects and each of its leaves through the same interface is the purpose of the Composite pattern, which is developed in a future article of this series.