Last active
July 20, 2025 07:06
-
-
Save arjunprakash027/6de5faa89369d1a4f4d8209404289ca6 to your computer and use it in GitHub Desktop.
Using Yield as intermediate state update mechanism in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Goal: show how a generator can flush an “early” state patch | |
| before a slow computation finishes. | |
| """ | |
| import time | |
| from copy import deepcopy | |
| # ── 1. The “state object” we want to keep in sync ────────────────────────── | |
| state = {"is_loading": False, "result": None} | |
| # ── 2. A helper that mimics Reflex’s diff-and-patch emitter ──────────────── | |
| def flush(prev: dict, curr: dict): | |
| """Print only the keys whose values changed.""" | |
| patch = {k: v for k, v in curr.items() if prev.get(k) != v} | |
| if patch: | |
| print("PATCH ➜", patch) | |
| # ── 3. Slow worker (pretend this is Pandas, network, etc.) ───────────────── | |
| def process_state(value: int) -> int: | |
| time.sleep(2) # heavy work (blocking) | |
| return value * value | |
| # ── 4. The *generator* handler with a single `yield` ─────────────────────── | |
| def handle_submit(x: int): | |
| state["is_loading"] = True # set busy flag | |
| yield # ✧ early flush here ✧ | |
| state["result"] = process_state(x) | |
| state["is_loading"] = 'MOnkey' # set busy flag | |
| yield | |
| state["result"] = process_state(x*45) | |
| state["is_loading"] = False # clear flag | |
| # (generator ends – final flush happens in driver) | |
| # ── 5. A tiny “event loop” that drives the generator ─────────────────────── | |
| def run_handler(gen): | |
| prev = deepcopy(state) # snapshot before we start | |
| while True: | |
| try: | |
| next(gen) | |
| except StopIteration: | |
| break | |
| finally: | |
| flush(prev, state) # first patch (is_loading=True) | |
| prev = deepcopy(state) | |
| # ── 6. Kick it off ───────────────────────────────────────────────────────── | |
| if __name__ == "__main__": | |
| print("-- click --") | |
| run_handler(handle_submit(7)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment