Architecture Patterns
Published by Brayan K
Master architectural patterns that separate concerns, enforce dependency rules, and build maintainable Python applications that scale from prototype to production
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Start with the rule that must survive a new interface
A stock-reservation rule should behave the same when called from a web form, a command-line tool or a background job. If the only validation lives in the web controller, another entry point can bypass it. Start by identifying that rule, rather than creating folders named “clean” or adding an interface for every class.
from dataclasses import dataclass
@dataclass(frozen=True)
class Stock:
quantity: int
def reserve(self, requested):
if type(requested) is not int or requested <= 0:
raise ValueError("requested quantity must be a positive integer")
if requested > self.quantity:
raise ValueError("not enough stock")
return Stock(self.quantity - requested)
original = Stock(5)
reserved = original.reserve(2)
print("original:", original.quantity)
print("after reservation:", reserved.quantity)
# ✅ Expected output:
# original: 5
# after reservation: 3The model returns a new value instead of mutating its input, so rejection cannot leave a half-applied subtraction. It assumes its starting stock is already valid; a database adapter must validate stored data and preserve that invariant too. This example models one operation, not a concurrent inventory system.
def remaining_stock(available, requested):
if type(requested) is not int or requested <= 0:
raise ValueError("requested quantity must be a positive integer")
if requested > available:
raise ValueError("not enough stock")
return available - requested
remaining_stock(5, 0)
# ✅ Expected error:
# ValueError: requested quantity must be a positive integerThe function and the small class express the same business rule. Neither style is automatically superior; simple data plus focused functions can be a good design. Data Classes & Advanced Class Patterns owns dataclass mechanics, and Functional Programming Techniques in Python owns pure functions.
MVC separates input, rules and presentation
In Model–View–Controller, the controller interprets input and invokes the model; the view presents the result. The model is not necessarily a database table. For a small program, these roles can be three functions in one file. Frameworks use the names differently, so trace the actual responsibilities instead of relying on a directory name.
def reserve(available, quantity):
if quantity <= 0 or quantity > available:
raise ValueError("quantity is outside available stock")
return available - quantity
def controller(form, available):
try:
quantity = int(form["quantity"])
except (KeyError, ValueError, TypeError):
return {"ok": False, "message": "enter a whole-number quantity"}
try:
remaining = reserve(available, quantity)
return {"ok": True, "remaining": remaining}
except ValueError as error:
return {"ok": False, "message": str(error)}
def text_view(result):
if not result["ok"]:
return "Cannot reserve: " + result["message"]
return "Remaining: " + str(result["remaining"])
for form in [{"quantity": "2"}, {"quantity": "many"}, {"quantity": "9"}]:
print(text_view(controller(form, available=5)))
# ✅ Expected output:
# Remaining: 3
# Cannot reserve: enter a whole-number quantity
# Cannot reserve: quantity is outside available stockForm parsing belongs at the input boundary; the stock rule still checks the parsed number. A second view could render the returned result differently without teaching the model about HTML, command-line colours or HTTP responses. The example does not persist stock, so each call starts from the supplied five units.
A controller should not grow into a function that parses inputs, runs SQL, decides stock policy, sends mail and builds presentation. Those changes have different reasons to happen. Separate them when that separation makes an actual workflow easier to change or test.
Clean Architecture makes the dependency point inward
An application use case coordinates an operation. It depends on the capability it needs, not on a particular database or web framework. An outer adapter supplies that capability. The small contract below is reserve(sku, quantity): atomically reserve positive stock and return the remaining quantity, or raise a clear failure. It intentionally does not expose SQLAlchemy rows to callers.
class MemoryStock:
def __init__(self, quantities):
self.quantities = dict(quantities)
def reserve(self, sku, quantity):
if type(quantity) is not int or quantity <= 0:
raise ValueError("quantity must be positive")
if sku not in self.quantities:
raise KeyError("unknown item")
available = self.quantities[sku]
if quantity > available:
raise ValueError("not enough stock")
self.quantities[sku] = available - quantity
return self.quantities[sku]
class ReserveStock:
def __init__(self, repository):
self.repository = repository
def execute(self, sku, quantity):
remaining = self.repository.reserve(sku, quantity)
return {"sku": sku, "remaining": remaining}
# Composition root: choose concrete collaborators here.
repository = MemoryStock({"notebook": 5})
use_case = ReserveStock(repository)
print(use_case.execute("notebook", 2))
try:
use_case.execute("notebook", 9)
except ValueError as error:
print("rejected:", error)
print("still available:", repository.quantities["notebook"])
# ✅ Expected output:
# {'sku': 'notebook', 'remaining': 3}
# rejected: not enough stock
# still available: 3The application receives its repository through the constructor: dependency injection needs no container library. The final setup is the composition root, where concrete adapters are chosen and connected. The use case does not create its own database or import a web request object.
This memory adapter is for sequential examples and tests. A production database adapter must implement the same reservation contract with a transaction or conditional update, not a vulnerable read-then-write sequence. Using SQLite & ORMs (SQLAlchemy) in Python owns those database mechanics. Swapping a class name alone does not make concurrency correct.
“Dependencies point inward” describes source-code dependencies: the core names the capability; an outer module implements it. Calls can still travel outward at runtime through the injected object. Keep package imports and circular-import mechanics with Module & Package Architecture for Large Codebases.
A fake tests a use case, not the real adapter
A recording fake can prove which repository call a use case makes, and whether it passes through the response. It cannot prove a real database's isolation, constraints or network behaviour. Keep a separate set of adapter integration checks for those facts.
class RecordingStock:
def __init__(self):
self.calls = []
def reserve(self, sku, quantity):
self.calls.append((sku, quantity))
return 3
class ReserveStock:
def __init__(self, repository):
self.repository = repository
def execute(self, sku, quantity):
remaining = self.repository.reserve(sku, quantity)
return {"sku": sku, "remaining": remaining}
fake = RecordingStock()
result = ReserveStock(fake).execute("notebook", 2)
assert fake.calls == [("notebook", 2)]
assert result == {"sku": "notebook", "remaining": 3}
print("calls:", fake.calls)
print("result:", result)
# ✅ Expected output:
# calls: [('notebook', 2)]
# result: {'sku': 'notebook', 'remaining': 3}The fake's constant response is intentional, and is not a real stock algorithm. Use the same contract tests against a memory adapter and the real adapter, including rejection and rollback cases. Test organisation, fixtures and assertions belong to Testing with pytest: Fixtures, Parametrisation & Mocks.
A misleading fake can make a broken design look correct. If it accepts negative quantities while the real adapter rejects them, tests of invalid requests are not testing the promised contract. Write down permitted inputs, returned values, failures and atomicity before adding more implementations.
An exception does not reverse an earlier side effect
Consider a reservation followed by a confirmation email. If mail fails after the stock change is committed, catching the exception cannot make the reservation disappear. The following in-memory model exposes the ordering problem without pretending to send mail or open a database.
state = {"stock": 5}
def reserve_and_notify(quantity, notify):
if quantity <= 0 or quantity > state["stock"]:
raise ValueError("invalid reservation")
state["stock"] -= quantity
notify()
def unavailable_mailer():
raise OSError("notification unavailable")
try:
reserve_and_notify(2, unavailable_mailer)
except OSError as error:
print(type(error).__name__ + ":", error)
print("stock after mail failure:", state["stock"])
# ✅ Expected output:
# OSError: notification unavailable
# stock after mail failure: 3The architecture must decide whether notification failure means the reservation failed, or whether a valid reservation now has a pending notification. Reporting “nothing happened” would be false. Database writes that form one use case can share a transaction, but an ordinary database transaction cannot roll back an email already delivered by another service.
One established design records both the reservation and a pending-message record in the same database transaction, then lets a worker deliver the message. This is an outbox. Delivery can repeat after a worker crash, so consumers need deduplication or an idempotent operation; “exactly once” is not established by adding a queue. This is a design option, not a claim that the small memory examples implement durable messaging.
When an operation spans repositories, an application-level transaction boundary or unit-of-work object can coordinate their database changes. Keep adapters from committing independently halfway through that operation. The transaction must end before the application reports durable success.
Wire the collaborator the use case actually receives
Complete the constructor assignment and method call. Creating a new repository inside execute() would bypass the injected test double and any configured database adapter.
class MemoryCatalog:
def title_for(self, item_id):
return {7: "Python Notes"}[item_id]
class FindTitle:
def __init__(self, catalog):
self.catalog = ___
def execute(self, item_id):
return self.catalog.___(item_id)
finder = FindTitle(MemoryCatalog())
print(finder.execute(7))
# 👉 replace ___ with catalog
# 👉 replace ___ with title_for
# ✅ Expected output:
# Python NotesBuild one use case with two presentations
Create a catalogue containing item 7, titled Python Notes, priced at 500 pence. Inject it into a Quote use case. For a positive quantity, return a dictionary with the title and total pence; reject zero or negative quantities. Write one text view and one dictionary view of that same result. Quote three copies, print both views, then demonstrate rejection of zero. Keep price calculation out of both views.
class MemoryCatalog:
def item(self, item_id):
items = {7: {"title": "Python Notes", "pence": 500}}
return dict(items[item_id])
class Quote:
def __init__(self, catalog):
self.catalog = catalog
def execute(self, item_id, quantity):
if type(quantity) is not int or quantity <= 0:
raise ValueError("quantity must be positive")
item = self.catalog.item(item_id)
return {"title": item["title"], "total_pence": item["pence"] * quantity}
def text_view(quote):
return quote["title"] + ": " + str(quote["total_pence"]) + " pence"
def dictionary_view(quote):
return {"item": quote["title"], "amount_pence": quote["total_pence"]}
use_case = Quote(MemoryCatalog())
quote = use_case.execute(7, 3)
print(text_view(quote))
print(dictionary_view(quote))
try:
use_case.execute(7, 0)
except ValueError as error:
print(type(error).__name__ + ":", error)
# ✅ Expected output:
# Python Notes: 1500 pence
# {'item': 'Python Notes', 'amount_pence': 1500}
# ValueError: quantity must be positiveThere is no need to add a service locator, singleton, event bus or abstract factory to this quote. Those are separate design choices; Design Patterns in Python (Singleton, Factory, Strategy) owns the named object-level patterns. Keep the simplest boundaries that let a real change happen in one place, and add a layer when you can name the problem it solves.
Practice quiz
A web form prevents reservations larger than stock, but a new command-line entry point bypasses that check. Where should the shared reservation rule live?
- In the web form parser before it creates the command
- In the HTML template that displays the stock level
- In the shared reservation logic used by both entry points
- In the command-line formatter that prints the result
Answer: In the shared reservation logic used by both entry points. An invariant must hold regardless of how the operation is invoked. Entry points parse input and views present results; the shared reservation logic enforces the stock rule.
Adding a text view duplicates the price calculation already used by an HTML view. Which change removes that duplication?
- Return application data once and let each view format it
- Copy the calculation into the new text-view function
- Let each view select its own database pricing rule
- Move HTML generation into the price-calculation function
Answer: Return application data once and let each view format it. Keep one use case for the calculation and give each presentation the resulting data. Choosing a view should not choose a different business rule.
A use case accepts a repository in its constructor but creates a concrete repository inside execute(). Why does its recording fake see no calls?
- The fake needs to create the concrete repository itself
- The composition root must also set a global repository
- The fake must use the same database as the concrete class
- execute() ignores the repository supplied to the use case
Answer: execute() ignores the repository supplied to the use case. Dependency injection only works when the use case actually uses the supplied dependency. Construct concrete adapters at the composition root, not inside the operation being tested.
A test with a recording fake checks the repository call count, its arguments and the use-case result. What remains unproved?
- Whether this test called its fake the expected number of times
- Whether the real adapter handles rollback and concurrent updates
- Whether this test passed the recorded arguments to its fake
- Whether this test returned the expected use-case result
Answer: Whether the real adapter handles rollback and concurrent updates. The fake proves the interaction exercised by this test. Real adapter transactions and concurrency require separate evidence; an in-memory implementation is not that evidence.
An in-memory stock value starts at 5. Reserving 2 changes it immediately; sending the confirmation then raises. The caller catches the error and performs no compensation. What stock value remains?
- 0
- 2
- 3
- 5
Answer: 3. The stock mutation happened before the mail failure. An exception does not reverse earlier side effects by itself; transaction and recovery boundaries must be designed explicitly.
A project has domain, adapters and presentation folders. Which import still breaks the intended inward dependency direction?
- The domain imports a concrete ORM repository
- An adapter imports the domain's repository contract
- The composition root imports a concrete adapter
- A presenter imports the application's result type
Answer: The domain imports a concrete ORM repository. Folder names do not enforce dependency boundaries. Keep the core independent of concrete storage adapters, and wire those adapters at the outer composition root.
An outbox worker delivers a message, then crashes before marking it sent. The retry delivers the same message again. What lets the consumer avoid applying its effect twice?
- Generate a new message ID for each delivery attempt
- Deduplicate only by the identity of the sending worker
- Mark every message complete before applying its effect
- Deduplicate using a stable ID for the original message
Answer: Deduplicate using a stable ID for the original message. A delivery can repeat after a crash. Use a stable message identity with durable, correctly coordinated deduplication; a new ID defeats that check, while acknowledging first can lose work.
A small quoting tool needs a second presentation of the same calculation. Which first change keeps the existing rule in one place?
- Duplicate the calculation into a new presentation module
- Reuse the quote use case and add a view for its result
- Move the calculation into the new text-formatting function
- Make the use case assemble both HTML and text output
Answer: Reuse the quote use case and add a view for its result. A second presentation does not require a second calculation or a new architecture for the whole application. Reuse the existing use case and adapt its result at the boundary.
Continue this course
- Previous: Integrating Python with Other Languages (C, Rust & more)
- Next: Slicing Lists & Strings — Extract sub-sequences with [start:stop:step], negative indices, and [::-1]
- Quick reference: Python cheat sheet