On this page

Collection di๏ƒ

๐ŸŸก Intermediate ยท Lesson 17

Collection DI - annotate list[Shape] and receive EVERY bound implementation in registration order. The plugin pattern in one annotation; zero matches is a legal empty list.

Before you run๏ƒ

Use the Intermediate guide for prerequisite concepts. Run from a checkout with Melder installed and Python 3.14 free-threading selected. The collection download includes the level's local helper modules.

Run the saved script๏ƒ

python UX_and_AIX_experiences/02_intermediate/17_collection_di.py
py -3.14t UX_and_AIX_experiences/02_intermediate/17_collection_di.py

Download this collection ยท Source on GitHub

Public surface๏ƒ

list[FrameType] collection injection

Code๏ƒ

 1"""
 2TIER: intermediate (17)
 3GOAL: Collection DI - annotate list[Shape] and receive EVERY bound
 4      implementation in registration order. The plugin pattern in one
 5      annotation; zero matches is a legal empty list.
 6SURFACE EXERCISED: list[FrameType] collection injection
 7"""
 8from typing import Protocol
 9
10import melder as md
11
12
13class Handler(Protocol):
14    def handle(self) -> str: ...
15
16
17class EmailHandler:
18    def handle(self) -> str:
19        return "email"
20
21
22class SmsHandler:
23    def handle(self) -> str:
24        return "sms"
25
26
27class Dispatcher:
28    def __init__(self, handlers: list[Handler]) -> None:
29        self.handlers = handlers
30
31
32def main() -> None:
33    book = md.Spellbook()
34    # One ACTIVE spell per (spellframe, binding_name) signature per
35    # frame - providers sharing a frame need distinct binding names.
36    book.bind(spell=EmailHandler, existence="unique", spellframe=Handler,
37              binding_name="email")
38    book.bind(spell=SmsHandler, existence="unique", spellframe=Handler,
39              binding_name="sms")
40    book.bind(spell=Dispatcher, existence="unique")
41    conduit = book.conjure()
42
43    dispatcher = conduit.meld(spell=Dispatcher)
44    results = [h.handle() for h in dispatcher.handlers]
45    assert results == ["email", "sms"]
46    print("collection DI delivered all implementations:", results)
47
48
49if __name__ == "__main__":
50    main()

Check the outcome๏ƒ

The script contains its own assertions or demonstrated refusal paths. Run it to evaluate those checks against your installed version. The code above is taken directly from the saved file; no run output is invented here.

More intermediate examples ยท Level guide