On this page

Factory functions๏ƒ

๐ŸŸข Beginner ยท Lesson 32

Two factory shapes, one law each - a FUNCTION spell is unique (one shared product); when you want a fresh object per meld, the factory must be a CLASS bound "many".

Before you run๏ƒ

Use the Beginner 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/01_beginner/32_factory_functions.py
py -3.14t UX_and_AIX_experiences/01_beginner/32_factory_functions.py

Download this collection ยท Source on GitHub

Public surface๏ƒ

function-unique law vs class-many freshness

Code๏ƒ

 1"""
 2TIER: beginner (32)
 3GOAL: Two factory shapes, one law each - a FUNCTION spell is unique
 4      (one shared product); when you want a fresh object per meld, the
 5      factory must be a CLASS bound "many".
 6SURFACE EXERCISED: function-unique law vs class-many freshness
 7"""
 8import melder as md
 9
10
11class Connection:
12    def __init__(self, dsn: str = "postgres://replica.example:5432/app") -> None:
13        self.dsn = dsn
14
15
16def shared_connection() -> Connection:
17    return Connection()
18
19
20def main() -> None:
21    book = md.Spellbook()
22    book.bind(spell=shared_connection, existence="unique",
23              spellframe="db", binding_name="shared-conn")
24    book.bind(spell=Connection, existence="many",
25              spellframe="db", binding_name="fresh-conn")
26    conduit = book.conjure()
27
28    a = conduit.meld(spellframe="db", binding_name="shared-conn")
29    b = conduit.meld(spellframe="db", binding_name="shared-conn")
30    print("function factory (unique): shared?", a is b)
31
32    c = conduit.meld(spellframe="db", binding_name="fresh-conn")
33    d = conduit.meld(spellframe="db", binding_name="fresh-conn")
34    assert c is not d
35    print("class factory (many): fresh per meld -", c is not d)
36
37
38if __name__ == "__main__":
39    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 beginner examples ยท Level guide