On this page

Constructor di by annotation๏ƒ

๐ŸŸก Intermediate ยท Lesson 15

THE DI heart - annotate a constructor parameter with a bound class and melder injects it. Dependencies resolve recursively; you meld the top and the graph assembles itself.

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/15_constructor_di_by_annotation.py
py -3.14t UX_and_AIX_experiences/02_intermediate/15_constructor_di_by_annotation.py

Download this collection ยท Source on GitHub

Public surface๏ƒ

type-hint constructor DI (SINGLE_BY_ANNOTATION)

Code๏ƒ

 1"""
 2TIER: intermediate (15)
 3GOAL: THE DI heart - annotate a constructor parameter with a bound
 4      class and melder injects it. Dependencies resolve recursively;
 5      you meld the top and the graph assembles itself.
 6SURFACE EXERCISED: type-hint constructor DI (SINGLE_BY_ANNOTATION)
 7"""
 8import melder as md
 9
10
11class Database:
12    def query(self) -> str:
13        return "42 rows"
14
15
16class ReportService:
17    def __init__(self, database: Database) -> None:
18        self.database = database
19
20    def run(self) -> str:
21        return "report over " + self.database.query()
22
23
24def main() -> None:
25    book = md.Spellbook()
26    book.bind(spell=Database, existence="unique")
27    book.bind(spell=ReportService, existence="unique")
28    conduit = book.conjure()
29
30    report = conduit.meld(spell=ReportService)
31    assert isinstance(report.database, Database)
32    print(report.run())
33    print("annotated the parameter; melder built the graph")
34
35
36if __name__ == "__main__":
37    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