On this page

Pass the conduit around๏ƒ

๐ŸŸข Beginner ยท Lesson 27

App structure 101 - main() owns the conduit and PASSES it to the functions that need things. Don't re-conjure, don't stash globals: the conduit is the world handle, hand it around like one.

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/27_pass_the_conduit_around.py
py -3.14t UX_and_AIX_experiences/01_beginner/27_pass_the_conduit_around.py

Download this collection ยท Source on GitHub

Public surface๏ƒ

the conduit as an argument

Code๏ƒ

 1"""
 2TIER: beginner (27)
 3GOAL: App structure 101 - main() owns the conduit and PASSES it to the
 4      functions that need things. Don't re-conjure, don't stash globals:
 5      the conduit is the world handle, hand it around like one.
 6SURFACE EXERCISED: the conduit as an argument
 7"""
 8import melder as md
 9
10
11class Mailer:
12    def send(self, to: str) -> str:
13        return "sent to " + to
14
15
16def welcome_new_user(conduit: md.Conduit, username: str) -> str:
17    mailer = conduit.meld(spell=Mailer)
18    return mailer.send(username)
19
20
21def main() -> None:
22    book = md.Spellbook()
23    book.bind(spell=Mailer, existence="unique")
24    conduit = book.conjure()
25
26    first = welcome_new_user(conduit, "ada")
27    second = welcome_new_user(conduit, "grace")
28    print(first)
29    print(second)
30
31    # The function got a real world handle, not a copy of one.
32    assert first == "sent to ada"
33    assert second == "sent to grace"
34
35    # AND IT IS THE SAME WORLD. `existence="unique"` means one Mailer, so
36    # two calls in two different functions melded the SAME object. That is
37    # the whole reason to pass the conduit instead of re-conjuring: a
38    # second conjure would have built a second world with its own Mailer,
39    # and these two would not be the same object.
40    assert conduit.meld(spell=Mailer) is conduit.meld(spell=Mailer)
41    print("one world handle, passed where needed - and the SAME Mailer")
42    print("  answered both calls, which is what re-conjuring would break")
43
44
45if __name__ == "__main__":
46    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