Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Objects with purpose
EXPERIMENT 45 / 101

Build with collaborators.

Make an object use a collaborator instead of inheriting every responsibility.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

Composition models a has-a relationship: a report service has a storage collaborator. Dependency injection means the collaborator is supplied from outside rather than constructed secretly inside. This keeps business behaviour separate from infrastructure and lets tests supply a small in-memory substitute.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

composition.py
class MemoryStore:
    def __init__(self):
        self.messages = []
    def save(self, message):
        self.messages.append(message)

class Reporter:
    def __init__(self, store):
        self.store = store
    def publish(self, name):
        self.store.save(f"Report: {name}")

store = MemoryStore()
Reporter(store).publish("Orbit")
print(store.messages)
↳ EXPECTED OUTPUT
['Report: Orbit']

03 Under the hood

  1. 1

    Reporter depends on the behaviour save(message), not on the details of a database driver.

  2. 2

    MemoryStore is an explicit, inspectable collaborator. A file or database store can provide the same interface without changing how the report is produced.

  3. 3

    This design makes tests narrow: assert that the expected report reaches the store. Do not create a large abstraction for every trivial function; introduce a boundary where there is real variation or an external dependency.

04 Your turn, builder

A SMALL MISSION

Inject a store into a notifier and verify that two messages arrive in the supplied store.

Reveal one possible solution +
one_possible_solution.py
class Store:
    def __init__(self): self.items = []
    def save(self, item): self.items.append(item)
class Notifier:
    def __init__(self, store): self.store = store
    def send(self, text): self.store.save(text)
store = Store()
notifier = Notifier(store)
notifier.send("Build")
notifier.send("Test")
print(store.items)

05 Check your signal

QUICK SIGNAL CHECK

What is injected into Reporter?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.