<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by KitFu Coda on Medium]]></title>
        <description><![CDATA[Stories by KitFu Coda on Medium]]></description>
        <link>https://medium.com/@kitfucoda?source=rss-6bb1e0cf9cd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XeHoZBQFytRe9x6MSOegjA.jpeg</url>
            <title>Stories by KitFu Coda on Medium</title>
            <link>https://medium.com/@kitfucoda?source=rss-6bb1e0cf9cd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:51:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kitfucoda/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spinning Wheels on Deep Sand: Debugging Python, Timezones, and the Art of Distraction]]></title>
            <link>https://python.plainenglish.io/spinning-wheels-on-deep-sand-debugging-python-timezones-and-the-art-of-distraction-c45b0349e489?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c45b0349e489</guid>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[work-life-balance]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 13:04:42 GMT</pubDate>
            <atom:updated>2026-10-02T09:58:42.066Z</atom:updated>
            <content:encoded><![CDATA[<h4>From misinterpreting a silent linter fix to building a custom sleep watcher — a story about code, friction, and learning when to pause.</h4><p>Whenever a beloved content creator who stayed inactive long enough suddenly releases a new work, people would joke about it saying they finally found the password. Yes, please go back to them and advocate the use of a reputable password manager. Meanwhile we can discuss a follow-up to the now 2-month-old story about <a href="https://kitfucoda.medium.com/orchestrating-long-running-interactive-subprocesses-with-python-asyncio-43068100408c">managing a long-running application with Python</a>. Please dont forget to hit like and subscribe.</p><p>Oh, wrong platform, sorry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-HQG3gA-KHkqtzqtE2ZEyA.png" /><figcaption>Cute illustration generated by <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><h3>The Silent Stall</h3><p>Being a remote worker, most if not all of my work is done through a laptop. Keeping a long-running process in the background in such a setup as discussed previously raises one question: what to do when the machine sleeps?</p><p>Contrary to a popular belief, being a software engineer does not mean I type on a computer all day without stopping. Thinking about how code should be written is also part of the job. Some may doodle, scribble and sketch on a writing medium, and that would mean the computer may go to sleep due to inactivity.</p><p>For the record, I speak to a rubber duck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*62zSyrNiBLrk_oFH" /><figcaption>Photo by <a href="https://unsplash.com/@ross_savchyn?utm_source=medium&amp;utm_medium=referral">Rostyslav Savchyn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We live in a transitional age where LLMs are changing the way we work, though evaluating their output is still an essential part of the workflow. Inactivity in these cases is not the only reason a computer goes to sleep. Let’s not forget that being portable often means there are times when work is not bound to a fixed location. There are people who leave the lid open while moving about, but this is definitely not a norm.</p><p>When my laptop goes to sleep, my script enters into an unknown state where the background process is seemingly dead but the script’s while loop stalls. Eventually I started exploring what could be done. With the help of an LLM, we misdiagnosed the problem together (spoiler alert?). This then led to a confidently written coroutine such that the script exits when a sleep is detected.</p><p>Now you know why it is crucial to evaluate what the chatbot returns, as you are about to see later.</p><h3>The False Fix</h3><p>Alright, if the computer sleeps, the script should just exit. How do we do this, and why is exiting on sleep the result of a misdiagnosis?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*53ES-nj9QnYCiGDI" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s answer the first question first, we can start with the monotonic function in the time module. As defined in the <a href="https://docs.python.org/3/library/time.html#time.monotonic">official documentation</a>, it returns a time that keeps increasing. By itself it has no meaning, the value is only useful when compared to another call.</p><p>Recall the premise: the computer sleeps. The implication of this is that when a program resumes from sleep, the subsequent monotonic call does not backfill the time spent in sleep. As an example, suppose we run a fictional program written in Python, and on the start of execution, monotonic returns 0. Say 3 seconds later, the computer goes to sleep for 5 seconds. When it comes back, this fictional program would return a 3 when we call monotonic instead of 8. In other words, the time spent sleeping does not advance the monotonic clock.</p><p>Figuring out whether the computer was sleeping can be done by comparing the real-world elapsed time and the difference between current and the starting return value of monotonic call. In normal circumstances the values should agree with negligible differences. Disagreement only happens when we are comparing both after the program resumes execution from sleep. In code form, this is roughly:</p><pre>import time<br><br># at the beginning of program<br>wall_start = time.time()<br>mono_start = time.monotonic()<br><br>(...)<br><br># after some time<br>wall_diff = time.time() - wall_start<br>mono_diff = time.monotonic() - mono_start<br><br># decide a threshold in seconds<br>THRESHOLD = 5<br><br># check if the program was paused <br># because the machine went to a sleep<br>if wall_diff - mono_diff &gt; THRESHOLD:<br>    print(&quot;Sleep detected&quot;)</pre><p>Back in our script that manages the background process, we can now adapt the snippet above into a coroutine that periodically checks the differences running alongside the management loop.</p><pre>import asyncio<br>from time import time, monotonic<br><br>RETRY_TIMEOUT = 5<br>SLEEP_THRESHOLD = 5<br><br>async def sleep_watcher(exit_event: asyncio.Event):<br>    start_wall = time()<br>    start_mono = monotonic()<br><br>    while not exit_event.is_set():<br>        elapsed_wall = time() - start_wall<br>        elapsed_mono = monotonic() - start_mono<br><br>        if elapsed_wall - elapsed_mono &gt; SLEEP_THRESHOLD:<br>            exit_event.set()<br>            break<br><br>        await asyncio.sleep(RETRY_TIMEOUT)<br><br><br># remember to also schedule the watcher alongside the main coroutine loop<br>asyncio.create_task(connect(..., exit_event))<br>asyncio.create_task(sleep_watcher(exit_event))</pre><p>Testing was easy. I started the script, closed the lid and waited. Once the laptop slept long enough, I lifted the lid back up and ta-da the script resumed and then exited.</p><p>Cue happy ending BGM.</p><p>Except, just two days ago, the background process that the script manages died prematurely, and the loop was stuck again. Ah, the classic curse of celebrating too early. Fortunately I had not started drafting this piece yet — just imagine the irony!</p><p>Turns out I made a mistake when I was comparing time in one of the coroutines:</p><pre>now = datetime.now(timezone(timedelta(hours=8)))<br>target = datetime.combine(now.date(), TARGET_HOUR)<br><br>now &gt;= target</pre><p>The fix is simple: supply the tzinfo=now.tzinfo into the call to datetime.combine. You can go figure why the comparison statement fails without it, just don’t tell my teacher.</p><p>Now we can really celebrate.</p><p>Patching the problem reminded me that the script worked in the beginning — so what went wrong then? The answer only came to me when I was planning this article halfway. Guess what? It was caused by me running the script through a linter in my editor when I was preparing the previous piece. I was asked to add a timezone to datetime.now. Clearing that from linting errors unknowingly broke the comparison statement.</p><p>Again, my teacher doesn’t need to know.</p><p>Despite the detour, the misdiagnosis still turns into an interesting learning experience. I wouldn’t have known how to detect a system sleep programmatically.</p><h3>Friction and Flame</h3><p>I can’t tell if this is just purely by chance, but planning this article forced me into reflecting on my work in general. Have I been pushing myself so hard that I am missing out on other things in other aspects of life?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LqfNe7wHSVGhZLld" /><figcaption>Photo by <a href="https://unsplash.com/@hariskhan488?utm_source=medium&amp;utm_medium=referral">Haris khan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Much like the script, I pushed myself almost to the limit entering a job that was completely foreign to me. New problems to solve, new language, this combination sounds like the exact thing people celebrate when they hear about breaking into uncharted territory. It wasn’t my first attempt exploring new things, but this time, it felt as though I had ventured way too far outside my comfort zone.</p><p>Unexpectedly stalling in an unknown state eerily resembles my attempt at physical recovery throughout the year. To a certain extent, “you have got to relax” became the sentence I want to avoid the most whenever I visit a new doctor (Chinese or Western medicine), or even a chiropractor.</p><p>It is hard to shake off the feeling that I am avoiding the real issue.</p><p>On the other hand, the difficulties I am facing at work to bridge the knowledge gap quickly enough manifests as real-world issues. Some of those may be painfully obvious like the timezone problem we just fixed.</p><p>As an analogy, it feels a lot like driving on thick sand, where the wheels spin wildly in place. Little progress is made, yet the body starts emitting signals of exhaustion from pushing too hard — not unlike an engine overheating from all the spinning.</p><p>At least, that’s how the professionals explain the cause of my stiff muscles and inflammation that turned chronic.</p><h3>The Unhandled Exception</h3><p>Life can be seen as a continuous cycle of events that we participate in. Things happen and end only for the next wave to arise and inevitably pass. The big question is: should I introduce a sleep_watcher equivalent into my life, giving myself a chance to pause?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*apxKJOxF5AHwoQP5" /><figcaption>Photo by <a href="https://unsplash.com/@itspootie?utm_source=medium&amp;utm_medium=referral">Alan Tang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Unfortunately, I am right on the verge and a decision needs to be made within the coming days. All of the available options that I am aware of lead to a different kind of adventure that I have no prior experience with. Ultimately, each choice would be a leap of faith without knowing where I will land.</p><p>I wish I could write an inspiring ending so I could proudly pretend to be an influencer that promotes positivity. That, however, is not how life works. Hard decisions need to be made and unknown consequences are also often part of the deal. Perhaps when I finally find time for the next piece we can then continue the story together?</p><p>Now where did I sync my teacher’s contact to?</p><p>This essay was authored entirely by the writer, with Gemini acting as an adaptive editorial sounding board for sentence-level polishing, structural flow analysis, and thematic brainstorming throughout the drafting process.</p><h3>Extended readings</h3><p><a href="https://kitfucoda.medium.com/orchestrating-long-running-interactive-subprocesses-with-python-asyncio-43068100408c">Orchestrating Long-Running, Interactive Subprocesses with Python Asyncio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c45b0349e489" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/spinning-wheels-on-deep-sand-debugging-python-timezones-and-the-art-of-distraction-c45b0349e489">Spinning Wheels on Deep Sand: Debugging Python, Timezones, and the Art of Distraction</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orchestrating Long-Running, Interactive Subprocesses with Python Asyncio]]></title>
            <link>https://python.plainenglish.io/orchestrating-long-running-interactive-subprocesses-with-python-asyncio-43068100408c?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/43068100408c</guid>
            <category><![CDATA[developer-life]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Sun, 19 Jul 2026 06:47:22 GMT</pubDate>
            <atom:updated>2026-09-05T15:43:45.934Z</atom:updated>
            <content:encoded><![CDATA[<p>Realizing our perception of time can change drastically when we are drowning in work is a rather funny experience. Reading the publishing date of the last article nearly gave me a good shock when I realized it was done half a year ago. Yet, it felt recent, and the follow-up to the project is still sitting in the filesystem awaiting planning and drafting.</p><p><a href="https://python.plainenglish.io/actor-models-in-pygame-lessons-in-serialization-and-state-isolation-979c5af57cc5">Actor Models in Pygame: Lessons in Serialization and State Isolation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R74ZBNUAXxeERoONFiK3NA.png" /><figcaption>Cute illustration generated by <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><p>Unfortunately, that story has to wait for a bit, as we are side-tracking to a different territory today. Definitely not a reflection of my current job situation where I am struggling outside of my comfort zone. Alrighty, let’s move on from this bad self-deprecating joke. Instead, we are abruptly revisiting Python subprocess management with AsyncIO as if nothing happened.</p><h3>The Limits of Shell Scripting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lgh1QsIwhuoHBCQu" /><figcaption>Photo by <a href="https://unsplash.com/@crawnical?utm_source=medium&amp;utm_medium=referral">Charles Asselin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are times where we utilize shell scripting to automate some tasks, but to what extent should we stick with just a scripting language? With LLM getting so much more capable these days, does the choice of tool still matter?</p><p>Our last attempt was about <a href="https://kitfucoda.medium.com/video-data-io-through-ffmpeg-subprocess-c5f1ee42e43d">passing data from one utility to another</a>, from a video encoder to a streamer (both ffmpeg executed with different arguments). There’s no data to be passed between processes this time, and we are just dealing with one process at a time. Sounds like a trivial shell script to write, an LLM chatbot would be more than enough for the job, that’s what I thought.</p><p><a href="https://kitfucoda.medium.com/video-data-io-through-ffmpeg-subprocess-c5f1ee42e43d">Video data IO through ffmpeg subprocess</a></p><p>Fortunately, Gemini flash did deliver.</p><p>Some additional background to the problem is likely warranted before we dive deeper. It is indeed true that we are not passing data between processes, but the process we are interested in managing does require some user interaction, both directly and indirectly through the command line interface. Another annoyance is that it would just silently terminate on failure and that affects my well-being.</p><p>Because when it terminates, I allow my partner to punch me in the face.</p><p>It was clearly a joke.</p><p>But you get the point.</p><p>Getting the utility in question to re-run on failure is then Gemini’s first attempt to turn the work into a shell script written in bash.</p><h3>Modern Prototyping with AI Autocomplete</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SUMnREkdv6KlVAzf" /><figcaption>Photo by <a href="https://unsplash.com/@barbarazandoval?utm_source=medium&amp;utm_medium=referral">Barbara Zandoval</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Writing the script in Bash is a fine choice, the utility does work as expected. Gemini gave me a script that looks maintainable, and like many sane, lazy coders (please disregard the adjective combination), I started piling more requirements to the original problem.</p><p>This experience of treating an LLM chatbot as my Santa does make me wonder — with the overly primitive constructs and toolchain, am I expecting bash to do too much?</p><p>Welcome to the show, where I get Gemini to turn my laziness into cryptic bash code.</p><p>First request was simple, we all like easy things. Though not a needy person, I do want to make myself available to my partner after certain hours. Dear chatbot, do not retry after dinner time.</p><p>The code was generated; Gemini obliged.</p><p>But there were times I needed it for a one-off fling, and the script wouldn’t co-operate. My partner continued to enjoy his victory over my oversight — until another revision to let it simulate a do-while loop, to run at least once and do the I-want-my-me-time guard check after the first iteration.</p><p>Besides interacting with it through the command line interface, the execution of the utility also halts temporarily when it is awaiting input through my cellphone. Think of it as a wellness check procedure; imagine I am preparing to shop for an expensive toy through a website, and it automatically asks for my partner’s approval.</p><p>I feel like someone just said no from a distance, as I am typing this.</p><p>Not just in my head, I hope.</p><p>Before I knew it, the bash script was already spawning subshells, keeping track of the process ID and trapping SIGTERM in case the user wants to jump into his partner’s arms. Getting it to quit when I fail to respond to my cellphone in time turns the script into gibberish that I can no longer comprehend.</p><p>Oh, the generated code was also broken, and I sincerely do not blame Gemini.</p><p>I would whack the user if I were the chatbot.</p><p>Pay for Pro subscription!</p><h3>Building a Non-Blocking Process Manager in Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VEYwfYPiOfW1ReP9" /><figcaption>Photo by <a href="https://unsplash.com/@rp_fstops?utm_source=medium&amp;utm_medium=referral">Raja Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>My incompetency with Bash eventually led to a script that I cannot personally maintain. Paying for Pro subscription over this is dumb, and that made me rethink my choices in life. What if I had done this in Python from the very beginning, where it has all the bells and whistles for the job.</p><p>Looking at the monstrosity, I got fed up with getting Gemini to fix it further. Just to be very frank, I couldn’t even pin-point where things were done incorrectly. That was when I reminded myself of the video encoding project I did earlier.</p><p>Essentially, the problem can be written in a coroutine function similar to</p><pre>async def connect(exit_event: asyncio.Event, password: str, timeout : int = KILL_TIMEOUT):<br>    logger = logging.getLogger(&#39;Connect&#39;)<br><br>while not exit_event.is_set():<br>        logger.info(&quot;Running utility&quot;)<br><br>        await interact(<br>            await asyncio.create_subprocess_exec(<br>                &#39;some-utility&#39;,<br>                stdout=asyncio.subprocess.PIPE,<br>                stderr=asyncio.subprocess.STDOUT,<br>                stdin=asyncio.subprocess.PIPE<br>            ),<br>            password,<br>            timeout,<br>            exit_event<br>        )<br><br>        logger.info(&quot;Process exited, waiting before retrying&quot;)<br>        await asyncio.sleep(RETRY_TIMEOUT)<br><br>        if is_past_off_hour():<br>            logger.info(&quot;Not repeating connection, exiting loop&quot;)<br>            break<br><br>    logger.info(&quot;Exiting connection loop&quot;)<br>    exit_event.set()</pre><p>Being increasingly more capable, LLM chatbots took over 70–80% of my programming work. As a result, I forgot that I had autocompletion configured in my editor. After drafting the core coroutine above, I started typing the function signature for all the interaction, and suddenly I was greeted with a somewhat usable draft.</p><pre>async def interact(process: asyncio.subprocess.Process, password: str, timeout : int, exit_event: asyncio.Event):<br>    logger = logging.getLogger(&#39;Command output&#39;)<br><br>    is_success = asyncio.Event()<br><br>    tasks = (<br>        asyncio.create_task(interact_timeout(process, timeout, is_success, exit_event)),<br>        asyncio.create_task(interact_kill(process, exit_event))<br>    )<br><br>    process.stdin.write(f&quot;{password}\n\n&quot;.encode(&#39;utf-8&#39;))<br><br>    await process.stdin.drain()<br><br>    while process.returncode is None:<br>        line_bytes = await process.stdout.readline()<br><br>        if not line_bytes:<br>            break<br><br>        line = line_bytes.decode(&#39;utf-8&#39;).strip()<br>        logger.info(&quot;%s&quot;, line)<br><br>        if is_success.is_set() and re.search(r&quot;PARTNER APPROVED&quot;, line):<br>            is_success.set()<br><br>    for task in tasks:<br>        if task.done() is False:<br>            task.cancel()<br><br>    await process.wait()</pre><p>Unlike the main coroutine that manages the overall retry-until-me-time setup, the interact coroutine manages each session with the process created by executing the utility. As mentioned, it expects some interaction via the command line interface through STDIN, hence the `process.stdin.write` call to input a sequence of characters expected by the utility.</p><p>Capturing the success state is also crucial, and we do that by checking the execution output for a certain string (The string PARTNER APPROVED in the mock example). After the corresponding event is set, we cancel the interaction timeout, as shown below</p><pre>async def interact_timeout(process: asyncio.subprocess.Process, timeout: int, has_dns: asyncio.Event, has_route: asyncio.Event, exit_event: asyncio.Event):<br>    logger = logging.getLogger(&#39;Timeout killer&#39;)<br><br>    await asyncio.sleep(timeout)<br><br>    if not is_success.is_set():<br>        logger.error(&quot;Timeout waiting for connection, killing process and sending event to exit&quot;)<br>        process.terminate()<br>        exit_event.set()<br>      return</pre><p>Lastly, we need to be able to terminate the process whenever desired — such as when we send a SIGTERM to the script.</p><pre>async def interact_kill(process: asyncio.subprocess.Process, exit_event: asyncio.Event):<br>    logger = logging.getLogger(&#39;Exit killer&#39;)<br><br>    await exit_event.wait()<br><br>    logger.info(&quot;Exit event set, killing process&quot;)<br>    process.terminate()</pre><p>Trapping the SIGTERM event can be done through the snippet shown below, adapted from the snippet <a href="https://kitfucoda.medium.com/asyncio-task-management-a-hands-on-scheduler-project-bd7b7fe58c7e">we discussed previously</a></p><p><a href="https://kitfucoda.medium.com/asyncio-task-management-a-hands-on-scheduler-project-bd7b7fe58c7e">AsyncIO Task Management: A Hands-On Scheduler Project</a></p><pre>@dataclass<br>class ShutdownHandler:<br>    exit_event: asyncio.Event<br><br>    def __call__(<br>        self, signum: int | None = None, frame: FrameType | None = None<br>    ) -&gt; None:<br>        logger = logging.getLogger(&#39;ShutdownHandler&#39;)<br><br>        logger.info(&quot;Sending exit event to all tasks in pool&quot;)<br><br>        self.exit_event.set()<br><br>        for task in asyncio.all_tasks():<br>            if task is not asyncio.current_task():<br>                task.cancel()<br><br>exit_event = asyncio.Event()<br>shutdown_handler = ShutdownHandler(exit_event)<br><br>for sig in (signal.SIGINT, signal.SIGTERM):<br>    asyncio.get_event_loop().add_signal_handler(sig, shutdown_handler)</pre><p>Seeing the LLM autocompletion feature in action is both a magical and creepy experience. Most of the time it made the work a breeze, especially when it correctly predicted what I had in mind. On the other hand it really felt like someone is watching over my shoulder constantly.</p><p>Developing the script took about an hour, and that included testing to ensure things work as expected. AsyncIO proved to be the right call, as the non-blocking nature ensured the process would terminate if I failed to respond on my cellphone in time. The orchestration would be significantly more complex should we do this synchronously.</p><p>Not like asynchronous code is any easier to read and comprehend anyway.</p><p>Pick your poison.</p><h3>The Verdict: Architecture, Nix, and Portability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U3rB6utBgDnlaZ4q" /><figcaption>Photo by <a href="https://unsplash.com/@niekdoup?utm_source=medium&amp;utm_medium=referral">Niek Doup</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I didn’t put in too much effort once I got it running. All I did was taking ideas from my past projects and assemble them together for the use case. No test suite was written, and yet, it worked fine. I guess it is time to answer the core question: was rewriting this in Python the right call?</p><p>It was definitely written to fit my own unique use-case, so there’s no concern about distributing or sharing it with others. Considering it is one of those execute-and-forget (with mostly minimal intervention) programs, having it written in a language I am more comfortable with is crucial. I am sure given enough time and effort, I could get Gemini to generate a usable bash equivalent, but I would rather spend that time on things that matter.</p><p>Like hugging my partner.</p><p>One peculiar discovery during the rewrite was realizing macOS Tahoe is still shipping with Python 3.9. Despite trying to not rely on modern tooling for this humble project (e.g. skipping uv for project management and ruff for linting), the new language constructs brought by 3.10 were too good to miss. Fortunately I already manage my environment with Nix’s home-manager, so setting up 3.10 by default was a no-brainer.</p><p><a href="https://blog.stackademic.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59">Beyond rbenv and pyenv: Achieving Reproducible Dev Setups with Nix</a></p><p>The implementation of timeout to terminate if I fail to respond to my phone in time is also done deliberately. Such interaction is usually time-sensitive, so if I miss it at first and return after a while it would have been expired anyway. Terminating the process on an assumption that I am absent is therefore a sensible choice.</p><p>As a conclusion to this side-project, yes, rewriting the small humble script in Python is the right call, purely because it makes it maintainable for myself. If you are reading this, the takeaway of this article is hopefully to show how much my partner tolerates my erratic behaviour.</p><p>I meant how AsyncIO can be helpful in such scenario.</p><p>While I didn’t publish the script in full, the snippets shown aren’t that much different from what we discussed in the past. Do let me know if you need help on managing a long-running process through AsyncIO.</p><ul><li><a href="https://kitfucoda.medium.com/understanding-awaitables-coroutines-tasks-and-futures-in-python-a9c12890d20d">Understanding Awaitables: Coroutines, Tasks, and Futures in Python</a></li><li><a href="https://kitfucoda.medium.com/asyncio-task-management-a-hands-on-scheduler-project-bd7b7fe58c7e">AsyncIO Task Management: A Hands-On Scheduler Project</a></li><li><a href="https://kitfucoda.medium.com/concurrency-vs-parallelism-achieving-scalability-with-processpoolexecutor-c366bfcc6207">Concurrency vs. Parallelism: Achieving Scalability with ProcessPoolExecutor</a></li></ul><p>Thanks again for reading this far, and I hope to write again soon and get back to Pygame programming</p><p>Finally, I’d like to acknowledge the editorial support provided by Gemini. While the code, architecture, and real-world trial and error are entirely my own, Gemini served as an essential second set of eyes — auditing sentence-to-sentence flow, refining tense consistency, and helping me balance the narrative arc between technical mechanics and personal storytelling. It was a true collaborative effort to ensure this chaotic development journey translates clearly on the page.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43068100408c" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/orchestrating-long-running-interactive-subprocesses-with-python-asyncio-43068100408c">Orchestrating Long-Running, Interactive Subprocesses with Python Asyncio</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actor Models in Pygame: Lessons in Serialization and State Isolation]]></title>
            <link>https://python.plainenglish.io/actor-models-in-pygame-lessons-in-serialization-and-state-isolation-979c5af57cc5?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/979c5af57cc5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 04:11:50 GMT</pubDate>
            <atom:updated>2025-12-30T12:54:05.850Z</atom:updated>
            <content:encoded><![CDATA[<p>Our attempt to build a prototype <a href="https://kitfucoda.medium.com/recreating-the-matrix-rain-with-pygame-manual-fades-and-the-transparency-of-code-ab24820ea4bd">recreating the matrix rain effect</a> last week forced us to revise the <a href="https://kitfucoda.medium.com/the-pygame-framework-i-didnt-plan-building-tic-tac-toe-with-asyncio-and-events-ea7ed54ec705">mini Pygame framework</a>. The implementation of the idea yielded a mixed result that I previously overlooked. No, it wasn’t due to my take on the Actor model, in case you’re wondering. What could the problem be then?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9CSjtSo3h1WF3k9RPI8Ug.png" /><figcaption>Cute doge on an adventure. Image courtesy of <a href="https://copilot.microsoft.com/">Microsoft Copilot</a>.</figcaption></figure><ul><li><a href="https://kitfucoda.medium.com/recreating-the-matrix-rain-with-pygame-manual-fades-and-the-transparency-of-code-ab24820ea4bd">Recreating the Matrix Rain with Pygame: Manual Fades and the Transparency of Code.</a></li><li><a href="https://kitfucoda.medium.com/the-pygame-framework-i-didnt-plan-building-tic-tac-toe-with-asyncio-and-events-ea7ed54ec705">The Pygame Framework I Didn&#39;t Plan: Building Tic-Tac-Toe with Asyncio and Events</a></li></ul><h3>The Vision: Searching for Order in the Matrix</h3><p>So what is this Actor model thing, you may wonder. Having originated from our experiment with Pygame through building a tic-tac-toe game, the framework was a “side-product” of the project. Extracting the framework out through refactoring was done in the hope of making it portable and applicable for other projects. It worked, as shown in the previous article, but it wasn’t perfect. We identified some problems too, namely inefficiency in the management of application state and the event dispatch lookups.</p><p>I can already hear criticism from afar saying the latter is just a design failure, but since we are fixing the data structure, why not just fix both in one go?</p><p>Jokes aside, let’s start by looking into the Actor model. Skipping a formal definition of the term, we let the code be a reference to the discussion. For the scope of this article, the model is merely something that looks like this sample code returned by Gemini.</p><pre>@dataclass<br>class UpdateState:<br>    &quot;&quot;&quot;Message to change state (Write)&quot;&quot;&quot;<br>    key: str<br>    value: Any<br><br><br>@dataclass<br>class GetState:<br>    &quot;&quot;&quot;Message to request state (Read)&quot;&quot;&quot;<br>    key: str<br>    reply_to: asyncio.Future  # Used to send the result back<br><br><br>async def producer(inbox: asyncio.Queue):<br>    &quot;&quot;&quot;Simulates a system event updating state (Write)&quot;&quot;&quot;<br>    await asyncio.sleep(1)<br>    print(&quot;[Producer] Sending update: score = 100&quot;)<br>    await inbox.put(UpdateState(&quot;score&quot;, 100))<br><br><br>async def consumer(inbox: asyncio.Queue):<br>    &quot;&quot;&quot;Simulates a UI element needing to read state (Read)&quot;&quot;&quot;<br>    await asyncio.sleep(2)<br>    print(&quot;[Consumer] I need the &#39;score&#39;...&quot;)<br>    <br>    # Create a &#39;return envelope&#39;<br>    future = asyncio.get_event_loop().create_future()<br>    await inbox.put(GetState(&quot;score&quot;, future))<br>    <br>    # Wait for the Actor to fill the envelope<br>    result = await future<br>    print(f&quot;[Consumer] Received score: {result}&quot;)</pre><p>A loop is running in the background reading from a queue (denoted by the inbox argument in the coroutine functions) expecting one of the two dataclasses above, each representing a type of request. When it is an UpdateState, the value is changed. Otherwise, the value is returned via the asyncio.Future. Some disassembly was done to the model to keep it simple, though essentially we now can restrict access to the state only through the mailbox (or inbox in the snippet).</p><p>On the other hand, fixing the event dispatch problem merely involves a slight redesign of the application state. Ideally, we should aim for a near <strong>O(1)</strong> performance, let’s just use a hashmap for the purpose, preferably a frozendict(). Roughly speaking, we want the application state that stores events handlers as shown below:</p><pre>@dataclass(frozen=True)<br>class Application:<br>    ...<br>    events: frozendict[tuple[Element, int], EventHandler]</pre><p>We are storing the handlers into a frozendict to stick with functional principles as much as possible. Immutability is the key to writing predictable and idempotent functions.</p><p>Another advantage of adopting the Actor model is it opens up a possibility of clean separation from other components. When there is a possibility of overdoing things, you may already know by now I am always there. My attempt to overengineer for the sake of learning eventually caused a major rewrite, though fortunately the implementation still centers around what we have discussed so far. Sit tight, as we are diving deep into an adventure full of misjudgments.</p><h3><strong>Trekking Inward: Drafting the Actor Blueprint</strong></h3><p>Doesn’t sound like an adventure so far?</p><p>Think of a request trekking into an application via a queue. The previous section would be like a roughly sketched overview map. Now is the time to join a relatively steady stream of requests. Looking at our map, we see some landmarks: a scheduler, a mailbox (basically a queue), some processing logic, and lastly a mechanism to reply. Implementing this in the context of our little Pygame framework is the goal we are trying to achieve here. There is some flexibility I wish to implement, specifically regarding how the request affects the application state.</p><p>Let’s start by requests.</p><p>An actor only responds to requests, and the outcome would be different depending on the types. Requests are then passed into an actor through a mailbox, in our case, a queue. Everything seems perfectly fine, until you see a small and almost illegible fine print in the map — Pygame is generally not thread safe, i.e. we run all Pygame code within the same thread. That means we need to be really aware when passing Pygame objects through queues, for instance, passing them through a multiprocessing Queue will end up a crash due to serialization failure.</p><p>Each request represents an action we want to do with the data, either a retrieval or a mutation. We start by defining a mutation request, the SetRequest:</p><pre>@dataclass<br>class Operation:<br>    op: Callable<br>    args: tuple = field(default_factory=tuple)<br>    kwargs: dict = field(default_factory=dict)<br><br><br>@dataclass<br>class SetRequest[Data]:<br>    operation: Operation<br><br>    async def __call__(self, data: Data) -&gt; Data:<br>        return await self.operation.op(<br>            data, *self.operation.args, **self.operation.kwargs<br>        )</pre><p>Instead of consolidating all the application state changes within one huge monolithic match-case statement, SetRequest delegates the mutation logic definition to the caller. Unfortunately, this also means the caller needs to be aware of the state’s internal structure. Despite that downside, the delegation should promote the caller to do a small, localized change to the state that holds multiple pieces of data.</p><p>On the other hand, there are cases where we want the current state. Retrieving multiple slivers of current state one at a time to complete a task can be rather inefficient as our requests could be stuck queuing up when traffic is busy, and that makes me think. The reason we are making the queries is to get things done; what if we bundle the processing logic over, like we did with SetRequest too? Rather than repeating the “fill in the blanks” exercise once for each sentence, we are doing the whole essay all at once. In short, bundling the retrieval requests into one execution request results in smaller queues. For that goal, we implement ExecuteRequest as such:</p><pre>@dataclass<br>class ExecuteReply:<br>    tag: UUID<br>    payload: Any<br><br><br>@dataclass<br>class ExecuteReplyTo:<br>    tag: UUID<br>    mailbox: Queue[ExecuteReply]<br><br><br>@dataclass<br>class ExecuteRequest[Data]:<br>    operation: Operation<br>    reply_to: ExecuteReplyTo | None = None<br><br>    async def __call__(self, data: Data) -&gt; None:<br>        result = asyncio.create_task(<br>            self.operation.op(data, *(self.operation.args), **(self.operation.kwargs))<br>        )<br><br>        if self.reply_to:<br>            asyncio.create_task(<br>                asyncio.to_thread(<br>                    self.reply_to.mailbox.put,<br>                    ExecuteReply(self.reply_to.tag, await result),<br>                )<br>            )</pre><p>In most cases, we do not expect the caller to care when the request is completed. What’s wrong with having an asyncio.Future like we saw earlier? The short answer is no, but I would like to defer this until we are discussing the overengineering part. Yet, if the caller cares about the reply, the request requires a recipient mailbox, and an identifier UUID for the recipient.</p><p>A scheduler is then built to bind everything together. It takes two arguments, namely the application state that it manages, and a mailbox that acts as the single point of entry for the state. Refer to the snippet below for a simplified implementation:</p><pre>async def state_scheduler[Data](state: [Data], mailbox: Queue[SetRequest[Data] | ExecuteRequest[Data]]):<br>    result = state<br>    while True:<br>        try:<br>            match request := await asyncio.to_thread(mailbox.get, timeout=0.001):<br>                case SetRequest():<br>                    result = await request(result)<br><br>                case ExecuteRequest():<br>                    asyncio.create_task(request(result))<br><br>        except Empty:<br>            pass</pre><p>Some may find the snippet resembles a reduce function that loops infinitely. On each iteration, the result should only get replaced if a SetRequest is received. Imagine if the state isn’t immutable, even the execute request would have a chance of breaking the integrity of the object. Both SetRequest and ExecuteRequest are also expected to <a href="https://kitfucoda.medium.com/the-versatility-of-call-a-python-developers-secret-weapon-a6bff776971a">implement the </a><a href="https://kitfucoda.medium.com/the-versatility-of-call-a-python-developers-secret-weapon-a6bff776971a">__call__ dunder</a> as shown in respective snippet. Remember the metaphor on bundling the “fill in the blanks” exercise into a callable when we discussed ExecuteRequest? It gets scheduled for execution here.</p><p><a href="https://kitfucoda.medium.com/the-versatility-of-call-a-python-developers-secret-weapon-a6bff776971a">The Versatility of __call__: A Python Developer&#39;s Secret Weapon</a></p><h3><strong>The Bumpy Ride: Overengineering the Parallel Dream</strong></h3><blockquote>“If it’s worth doing, it’s worth overdoing”</blockquote><p>I didn’t watch a lot of MythBusters growing up, but this motto has a special place in my heart. Hang on tight, this is also where our relaxing boat ride gets a little bumpy. The Actor model offers a possibility to cleanly separate the state away from the rest of the application. Seems like a good opportunity to further split the application to multiple processes right? The application state actor, display update loop, as well as the event dispatch loop will all run independently, right?</p><p>Let’s overengineer this project, because more processes in parallel means faster execution, right?</p><p>Running each component in a separate process is done through the usual ProcessPoolExecutor setup. Further discussion on the topic can be found in the <a href="https://kitfucoda.medium.com/concurrency-vs-parallelism-achieving-scalability-with-processpoolexecutor-c366bfcc6207">AsyncIO article series</a> and hence we are skipping the details here. Why dedicate a section for the topic then?</p><p>Remember we deferred the discussion of having an asyncio.Future for replies? Turns out AsyncIO has the same constraint as Pygame — the objects should stay within the thread. As we know, objects get serialized when they are sent through a cross-process queue. Recreating an asyncio.Future in another process will raise an exception, causing the execution to fail.</p><p>For the same reason, we are also avoiding sending Pygame objects through cross-process queues.</p><p>You might notice that ExecuteReplyTo takes a tag UUID and mailbox. According to the dataclass definition we know mailbox is another cross-process queue, but what does the tag identifier do?</p><p>It is a key to our registry of asyncio.Future that lives only in the caller’s process, as shown below:</p><pre>async def inbox_consume(<br>    inbox: Queue[ExecuteReply], futures: dict[UUID, asyncio.Future]<br>) -&gt; None:<br>    with suppress(Empty):<br>        reply = await asyncio.to_thread(inbox.get_nowait)<br><br>        if futures[reply.tag]:<br>            futures[reply.tag].set_result(reply.payload)</pre><p>Each process maintains its own registry and a cross-process queue. A loop is set up to run inbox_consume repeatedly such that the corresponding asyncio.Future objects get notified as soon as the reply arrives.</p><p>As an example, this is how it works in action:</p><pre>async def some_callable(state) -&gt; bool:<br>    ...<br><br>    return True<br><br><br>async def caller(...):<br>    done_future = uuid4()<br>    futures[done_future] = asyncio.Future()<br>    game_in.put(<br>        ExecuteRequest(<br>            Operation(some_callable),<br>            ExecuteReplyTo(done_future, futures_mailbox),<br>        ),<br>    )<br>    await futures[done_future]</pre><p>Here’s a brief explanation to the snippet above:</p><ol><li>All callables defined for SetRequest and ExecuteRequest receive the current state as the first argument</li><li>We register a new asyncio.Future to a UUID tag before firing the ExecuteRequest.</li><li>The tag and the future_mailbox to update the registry of asyncio.Future are sent as a ExecuteReplyTo object.</li><li>The bundled some_callable runs in the process where the state lives.</li><li>Back in the caller’s process, since the ExecuteRequest expects a return value, we perform a blocking await at the corresponding entry in the registry of asyncio.Future.</li></ol><p>Some Pygame objects are stored within the application state object, so it runs in the process that calls the Pygame API. While it seems like we managed to split the application into three separate processes, if we are delegating all requests back to the process that manages Pygame anyway, is the added complexity worth it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psFje8oVqYwFTul4IDmNuA.png" /><figcaption>Silently screaming at the low FPS</figcaption></figure><p>Grab onto something quick, as we are heading towards a waterfall.</p><h3><strong>The Waterfall: A 30 FPS Reality Check</strong></h3><p>Though there were hiccups, the code eventually ran. For a while I was quite proud of myself for getting everything assembled properly. I still remember the realization came about an hour later when I was staring at the code on pushing visual changes to the application window. That was the fall off a cliff moment. So what went wrong? The separation into multiple processes was not such a good idea eh?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hiD-KescU1f619nU" /><figcaption>Photo by <a href="https://unsplash.com/@adityachinchure?utm_source=medium&amp;utm_medium=referral">Aditya Chinchure</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Pygame.time.Clock has a method called .tick(). It is meant to be called once per frame. If a framerate is specified, it would block until time is up to prevent premature frame update. That practically means the callable sent by the process managing the display is going to be blocking the process hosting the scheduler for the Actor (which also holds the application state containing Pygame objects). Considering this callable also gets sent repeatedly in an infinite loop, it means the Actor process is constantly blocking, leaving little room for concurrency.</p><p>Another bottleneck that I underestimated is how the serialization works through the cross-process queue could potentially slow things down. If I was falling when the realization of the blocking operation happened, recognizing this bottleneck is when my boat and I plunged into the water down the cliff. The struggle to get back to the surface almost became measurable, when I started to compare the frame per second figures.</p><p>Instead of hitting the 60fps target, we are only seeing frame rate in the 30s. It is obvious that the added complexity that involves cross-process message passing is the culprit. Measuring is going to be hard, but I would imagine the constant conversion between an actual project and serialized form would contribute to the delay.</p><p>We are now stuck in the middle of nowhere; the expedition failed.</p><p>What’s next?</p><h3><strong>The Principled Pivot: Painting with Experience</strong></h3><p>We failed the mission to cleanly separate the components into independent processes. Despite that, I am still happy throughout the adventure. The expedition pushed me far enough from my comfort zone and all the insights gained were valuable. Failing is never a problem, as long as we are learning something through it.</p><p>Like many fellow engineers, I do have a fair share of failures when I write code. Every new project I work on is not unlike an expedition into the unknown. While the outcome is important, we need to be aware of every step we take too. If experience is a painting, the trail of foot steps is exactly how lines are formed in an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HxQ7bnnIcm3opyK5" /><figcaption>Photo by <a href="https://unsplash.com/@groove328?utm_source=medium&amp;utm_medium=referral">Andrey Novik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So what do we learn in this in-progress painting of our Pygame experiment?</p><p>Looking at the bright side, I really liked how the application state is now managed through the Actor model. After removing the multi-process setup, certain parts would be greatly simplified. Overall, it is much more manageable than my poorly implemented model. Another revision is definitely happening and hopefully the fps count recovers.</p><p>Lastly, thanks for another year of support, and I shall write again soon. Bonne Année.</p><p>Finally, I’d like to acknowledge the editorial and research support provided by Gemini in producing this write-up. While the architecture and the hard-learned lessons are mine, Gemini acted as a second set of eyes — helping me audit the sentence-to-sentence flow, cross-referencing patterns like the Active Object and the “Ask” pattern, and ensuring that my “expedition” through the code was as clear to you as it was bumpy for me. It’s been a collaborative effort to ensure that even my failures are presented with the technical rigor they deserve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=979c5af57cc5" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/actor-models-in-pygame-lessons-in-serialization-and-state-isolation-979c5af57cc5">Actor Models in Pygame: Lessons in Serialization and State Isolation</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recreating the Matrix Rain with Pygame: Manual Fades and the Transparency of Code.]]></title>
            <link>https://python.plainenglish.io/recreating-the-matrix-rain-with-pygame-manual-fades-and-the-transparency-of-code-ab24820ea4bd?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab24820ea4bd</guid>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 19:24:31 GMT</pubDate>
            <atom:updated>2025-12-30T12:53:50.646Z</atom:updated>
            <content:encoded><![CDATA[<p>Earlier in the year, we <a href="https://kitfucoda.medium.com/my-pygame-evolution-embracing-asyncio-and-immutability-for-scalable-design-84eae4601717">explored Pygame</a> by writing a <a href="https://kitfucoda.medium.com/the-pygame-framework-i-didnt-plan-building-tic-tac-toe-with-asyncio-and-events-ea7ed54ec705">simple tic-tac-toe game</a>. The exercise unexpectedly yielded a reusable mini framework. Despite being far from “production-ready”, it is still sufficiently good for smaller-scale experiments. One of the possible projects mentioned towards the end of the article was a remake of the <a href="https://kitfucoda.medium.com/code-rains-revelation-embracing-existence-before-perfection-60f5c641963a">video intro with the Matrix code rain effect</a>. Even though I phrased it as a joke at the time, we are diving into it in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JV3T2MwZDMlCxNhB8g9AQ.png" /><figcaption>A cute cartoon generated by my editor <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><ul><li><a href="https://kitfucoda.medium.com/my-pygame-evolution-embracing-asyncio-and-immutability-for-scalable-design-84eae4601717">My Pygame Evolution: Embracing Asyncio and Immutability for Scalable Design</a></li><li><a href="https://kitfucoda.medium.com/the-pygame-framework-i-didnt-plan-building-tic-tac-toe-with-asyncio-and-events-ea7ed54ec705">The Pygame Framework I Didn&#39;t Plan: Building Tic-Tac-Toe with Asyncio and Events</a></li><li><a href="https://kitfucoda.medium.com/code-rains-revelation-embracing-existence-before-perfection-60f5c641963a">Code Rain&#39;s Revelation: Embracing Existence Before Perfection</a></li></ul><h3><strong>Returning to the Source: A Baby-Steps Approach</strong></h3><p>We are taking a baby-steps approach in this remake project, as I am rather tied up with my full-time work commitments. In this installment, we are only focusing on the fade-out animation and will continue working towards a full recreation in the future. The fade-out effect in the animation was made possible through the use of jQuery’s .fadeOut() method, which fades an element out in a specified duration.</p><p>How do we do it in jQuery, one may wonder? The snippet below shows how it is being done in the context of a web application.</p><pre>&lt;!-- html --&gt;<br>&lt;p id=&quot;target&quot;&gt;Lorem ipsum dolor sit amet&lt;/p&gt;<br><br>&lt;script&gt;<br>  // jQuery<br>  $(&quot;#target&quot;).fadeOut()<br>&lt;/script&gt;</pre><h3><strong>Deconstructing the Magic: Recreating .fadeOut()</strong></h3><p>Now that we know how it’s done with jQuery, the logical next step is to start defining the problem. Revisions to the framework may be required if there’s a need to support the specific effect. Actual implementation comes a bit later, after drafting a proper plan. Read on to follow along.</p><p>What is the problem we are solving today?</p><p>We want to make it possible to render a character on the screen, and repeatedly re-render the character with a different alpha value until it reaches 0. Each character is expected to be rendered over a pygame.Rect and we are assuming there are no overlaps in our application. Additionally, the alpha value decreases linearly over the specified duration, which should keep the implementation simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnZ_hkd3mEvEEszZBpWAJw.gif" /><figcaption>a screen recording of the desired outcome</figcaption></figure><p>Next, we figure out what is needed from the framework. In order to trigger a re-render at a consistent interval, we need to post an event in our rendering loop. Let’s call it FRAME_NEXT, and add it to the enum of SystemEvent alongside the INIT event we saw in the tic-tac-toe project.</p><p>That yields an updated display_update function, as shown below:</p><pre>async def display_update(<br>    screen_update: asyncio.Queue, clock: pygame.time.Clock<br>) -&gt; None:<br>    clock.tick(60)<br><br>    updates = []<br><br>    with suppress(asyncio.queues.QueueEmpty):<br>        while element := screen_update.get_nowait():<br>            updates.append(element.position)<br><br>    pygame.display.update(updates)<br><br>    # Trigger new FRAME_NEXT event<br>    pygame.event.post(pygame.event.Event(SystemEvent.FRAME_NEXT.value))</pre><p>Printing a character to the screen is similar to how we draw a circle or a cross in the tic-tac-toe project. First, we draw a pygame.Rect, then we draw the rendered text surface object over it. Start by rendering the character, and we get the corresponding text_surface and the rect enclosing it:</p><pre>import pygame.freetype<br><br>font = pygame.freetype.Font(&quot;/path/to/font.ttf&quot;, font_size)<br><br>text_surface, rect = font.render(&#39;a&#39;, (red, green, blue, alpha))</pre><p>The self-explanatory font_size, red, green, blue, alpha are all integers, and the latter four are in the range of [0, 255].</p><p>Given both the text_surface and enclosing rect, we can print them to the screen at any desired location as follows:</p><pre># optionally we can move the rect<br>rect.topleft = (x, y)<br><br># first draw the backing rect<br>pygame.draw.rect(application.screen, (0, 0, 0), rect)<br><br># secondly draw the rendered character<br>application.screen.blit(text_surface, rect)</pre><p>We can finally assemble two functions, one to create an initial print, and another to update the region with the same character but with a different alpha value:</p><pre>@dataclass(frozen=True)<br>class CharElem(Element):<br>    value: str = &quot; &quot;<br>    font: pygame.freetype.Font | None = None<br>    color: tuple[int, int, int] = (0, 0, 0)<br>    alpha: int = 0<br><br><br>async def char_create(<br>    application: Application,<br>    value: str,<br>    size: int,<br>    color: tuple[int, int, int],<br>    alpha: int,<br>    position: tuple[int, int],<br>) -&gt; CharElem:<br>    assert len(value) == 1 and isinstance(value, str)<br><br>    font = pygame.freetype.Font(&quot;/path/to/font.ttf&quot;, size)<br><br>    surface, rect = font.render(value, (255, 255, 255, alpha))<br><br>    rect.topleft = position<br><br>    pygame.draw.rect(application.screen, (0, 0, 0), rect)<br>    application.screen.blit(surface, rect)<br><br>    return CharElem(position=rect, value=value, font=font, color=color, alpha=alpha)<br><br><br>async def char_update(application: Application, elem: CharElem, alpha: int) -&gt; CharElem:<br>    assert elem.position<br>    assert elem.font<br><br>    surface, _ = elem.font.render(elem.value, elem.color + (alpha,))<br><br>    pygame.draw.rect(application.screen, (0, 0, 0), elem.position)<br>    application.screen.blit(surface, elem.position)<br><br>    return replace(elem, alpha=alpha)</pre><p>Updating a drawn character returned by char_create is done through a handler listening to the FRAME_NEXT event we defined earlier. An extension to the usual element event handler is hence needed to hold two extra pieces of data: the duration and start time. Fortunately, this is trivial with the use of __call__ <a href="https://kitfucoda.medium.com/the-versatility-of-call-a-python-developers-secret-weapon-a6bff776971a">dunder</a>:</p><pre>@dataclass<br>class FadeOutHandler:<br>    duration: int<br>    start_time: int = field(default_factory=lambda: monotonic_ns() // 1_000_000)<br><br>    async def __call__(<br>        self,<br>        event: pygame.event.Event,<br>        target: CharElem,<br>        application: Application,<br>        logger: BoundLogger,<br>        **detail: Any,<br>    ) -&gt; None:<br>        current = monotonic_ns() // 1_000_000<br>        elapsed = current - self.start_time<br>        remaining = 1.0 - (elapsed / self.duration)<br>        alpha = int(max(255 * remaining, 0))<br><br>        elem = await char_update(application, target, alpha)<br><br>        asyncio.create_task(screen_update(application, elem))<br><br>        if alpha &gt; 0:<br>            asyncio.create_task(<br>                application.delta_data.put(<br>                    DeltaUpdate(ApplicationDataField.ELEMENTS, target, elem)<br>                )<br>            )<br>        else:<br>            asyncio.create_task(<br>                application.delta_data.put(<br>                    DeltaDelete(ApplicationDataField.ELEMENTS, target)<br>                )<br>            )</pre><p>Some points worth noting regarding the snippet:</p><ol><li>As with the .fadeOut(duration) offered by jQuery, we define the duration in milliseconds</li><li>We remain somewhat stateless by storing just the start_time, and we calculate the alpha value at any time by comparing it to the percentage of remaining time.</li><li>After alpha reaches 0, remember to remove the element reference from the application</li></ol><p><a href="https://kitfucoda.medium.com/the-versatility-of-call-a-python-developers-secret-weapon-a6bff776971a">The Versatility of __call__: A Python Developer&#39;s Secret Weapon</a></p><p>Registering the event can then be done through a helper function:</p><pre>async def fade_out(application: Application, elem: CharElem, duration: int) -&gt; CharElem:<br>    return await add_event_listener(<br>        elem,<br>        SystemEvent.FRAME_NEXT.value,<br>        FadeOutHandler(duration),<br>    )</pre><p>Are we done yet?</p><p>One last piece of the puzzle is the click event handler, where a character is shown and eventually fades out into oblivion wherever the user clicks on the screen.</p><pre>async def handle_click(<br>    event: pygame.event.Event, target: Application, logger: BoundLogger<br>) -&gt; None:<br>    elem = await fade_out(<br>        target,<br>        await char_create(target, &quot;a&quot;, 20, (255, 255, 0), 255, event.pos),<br>        1000,<br>    )<br><br>    asyncio.create_task(screen_update(target, elem))<br>    asyncio.create_task(<br>        target.delta_data.put(DeltaAdd(ApplicationDataField.ELEMENTS, elem))<br>    )</pre><p>We are almost done, though I am skipping the boilerplate bootstrapping code as it is rather similar to the tic-tac-toe application. Basically, the code sets up the window, paints the background colour, and registers the click event. For those interested, do check the <a href="https://github.com/Jeffrey04/kitfucoda-intro2">GitHub repository</a> for the complete application.</p><p><a href="https://github.com/Jeffrey04/kitfucoda-intro2">GitHub - Jeffrey04/kitfucoda-intro2</a></p><h3><strong>The Cracks in the Framework: Scalability and Loops</strong></h3><p>Some expansion to the framework was already done when I was building the tic-tac-toe game earlier. Apart from some small syntactic changes made to the API, I was pleasantly surprised to find the overall framework design was left untouched. That’s good news, no?</p><p>A revision to the DeltaOperation was done previously to consolidate all changes to the Application object into one queue. It was a sensible improvement to the original implementation, but I still don’t quite like the complexity of the queue consumption. Sooner or later scalability will become an issue we want to address when the need to draw hundreds of elements at a time arises.</p><p>Furthermore, another pain point occurs in the event dispatching loop. Ideally, we want a quick lookup that is close to O(1). Unfortunately, we are looping through elements followed by events on every cycle. Performance is definitely taking a hit as we are running everything concurrently and we are wasting so much time looping needlessly in lookup operations.</p><p>What’s next then? I suppose you may wonder where we are headed, if you are still following thus far.</p><p>Apparently the refactoring that was done to the DeltaOperation somewhat resembles the Actor model. Further research and experiments are needed to see how it fits the design. From what I know so far, the model offers a cleaner separation of data storage and retrieval logic from the rest of the application. Hopefully that possibility of clean separation allows some independence. This can be helpful as it enables us to further split different parts of the application to run in parallel. This would be challenging, given how Pygame is not even thread-safe.</p><p>That means the next installment should focus on the optimization instead of continuing the momentum of building the next feature — the chain of characters raining down the screen.</p><h3><strong>Visibility, Implementation, and Identity</strong></h3><p>Just to recap, we achieved the goal of building an almost equivalent to jQuery’s .fadeOut() effect that works with our mini Pygame framework. An exact copy is never the goal, considering the rendering technique is different and we are synchronizing the change with the frame rate. Implementing the gradual decrease of alpha value really does take some effort in designing and planning. This is truly an interesting learning journey and I hope you benefit from following along.</p><p>It really does make you appreciate all the work done to provide the functionality through a simple method call.</p><p>The reimplementation in this low-level setting leads to a personal reflection related to recent news that deeply saddens me. There seem to be ongoing raid operations targeting men-only wellness centres. In one of those operations, a video was leaked across social media where the arrested patrons could be seen unclothed. A list with enough identifying information sans the name was also circulated.</p><p>Every line of code written in the low-level setting is very explicit and corresponds to a visible consequence. This kind of transparency prompted a revelation where, as a gay man, it is crucial to increase the visibility of members of the sexual minority. There are a lot of us in society working earnestly and also actively taking part in our civil duties. It is important to recognize that everyone in society is multi-faceted. As long as no harm is caused, one’s private life should remain private. Judging a person solely on visiting a wellness centre is simply unfair. Even the authorities fail to bring the patrons to court due to lack of evidence in one of the raids. Unfortunately, some still faced repercussions at work, especially the public servants.</p><p>Hopefully you gain insights while reading the articles published here on KitFu Coda, which is my ultimate goal as a fellow engineer. My sexuality indeed doesn’t matter to the content, but it is the best way I could think of to voice my support and solidarity with those who are still suffering the consequences to this day.</p><p>Lastly, thank you for reading, and I shall write again soon.</p><p>This article was written with editorial assistance from Gemini to refine the language and structure. Please note that while the AI helped catch errors, all project ideas, code algorithms, and personal perspectives are my own original work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab24820ea4bd" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/recreating-the-matrix-rain-with-pygame-manual-fades-and-the-transparency-of-code-ab24820ea4bd">Recreating the Matrix Rain with Pygame: Manual Fades and the Transparency of Code.</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Concurrency Choreographer: Making BLE’s Async Data Sync with OBS]]></title>
            <link>https://python.plainenglish.io/the-concurrency-choreographer-making-bles-async-data-sync-with-obs-095db549d2fc?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/095db549d2fc</guid>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[bluetooth-low-energy]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 02:53:18 GMT</pubDate>
            <atom:updated>2025-11-26T16:39:21.041Z</atom:updated>
            <content:encoded><![CDATA[<p>“What can we do with asynchronous programming?”, This was one of the questions I received in my talk on asynchronous programming that I delivered in <a href="https://kitfucoda.medium.com/from-blog-post-to-pycon-my-one-week-crash-course-in-public-speaking-ab4987b75702">Pycon MY</a>. While I briefly mentioned building a chatbot that day. I believe the project we are discussing today should resonate more. During my spare time (however rare it is these days), I stream my gameplay session to document my journey. One of the widgets in my streaming session is a heart rate monitor, and it has been broken for some time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhPp68JeBibP6di42WaXHQ.jpeg" /><figcaption>Cute cartoon on the topic generated by <a href="https://gemini.google.com/">Gemini</a></figcaption></figure><h3>Seeking the Open Standard: From Fitbit’s Lock-in to Garmin’s BLE</h3><p>I was doing some spring-cleaning for my OBS setup, and one component caught my eye — the heart rate monitor. For a time, it was a novel way to convey a streamer’s psychological state in a numerical form. Coincidentally, I was already wearing a fitness tracker: Fitbit Versa 3 and I decided to give it a go. Fortunately, there was a way to capture heart rate through the somewhat limited proprietary API, and have it streamed to my computer. Problem is, the fitness (not so) smartwatch died.</p><p>Funnily enough, a family member bought an almost identical Fitbit Sense a few months earlier and her watch is still functioning as of now. In a way the watch died rather prematurely. On the other hand, <a href="https://kitfucoda.medium.com/beyond-the-code-a-lunar-new-year-reflection-on-career-recovery-and-new-beginnings-81f89d695478">I was out of a job</a>, and yet that didn’t translate to more gaming time as I was juggling with multiple things at the time. Consequently, the replacement only came much later, not long after I started my current job. Instead of getting another Fitbit, I moved on to a Garmin Instinct II, a tracker my peers highly recommended.</p><p>Unlike my past Fitbit devices, the Garmin watch does broadcast my heart rate via a standard Bluetooth interface. This makes replacing the workflow a much easier job. For that to work, I just needed to figure out how to get the data, and then supply that data to OBS via the WebSocket interface. The library in use is bleak to communicate with the watch via Bluetooth LE, and obsws-python to publish heart rate to OBS.</p><p>Previously, our chatbot project only dealt with asynchronous libraries. Yet, this time the library that communicates with OBS is synchronous. Therefore, we are taking this opportunity to discuss how to coordinate them to work with each other. Specifically, we are solving the problem where the producer (the heart rate monitor data) is asynchronous, and the consumer (the sending of heart rate to OBS) is synchronous.</p><h3>Building the Async Producer: Connecting via Bluetooth Low Energy</h3><p>My journey on tracking my fitness data started with reading about running. One of the books I read was titled <em>Body, Mind and Sport</em> by John Douillard. Some of the practices advocated may seem controversial, though the idea of being mindful about my physical state stuck in my mind. As a result, I started running with deep breaths, and soon noticed running could be made bearable or even enjoyable with some effort. At the same time, I went looking for a chest belt to pair with my fitness tracker installed on my phone.</p><p>That was before wearable tech went mainstream, so my choices were rather limited. Chest straps to measure heart rate were common among runners, but they weren’t built to work with Bluetooth. I had to search high and low to finally find one that would work with my smartphone application. It was slightly more expensive than an ordinary tracker, but it was worth it. I ran with it for a few years, and benefited from having my current heart rate displayed on my tracker in real time.</p><p>No more estimating by poking my fingers to my neck and doing multiplication while I was busy catching my breath.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hKnfzx0ERmDh3wY1" /><figcaption>Photo by <a href="https://unsplash.com/@luizr_ph?utm_source=medium&amp;utm_medium=referral">Luiz Rogério Nunes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When wearable technology started to take off, Sony later released their smart band. The companion app also provided some limited insight on how my body reacts to activities in my day-to-day life. Conveniently, it also broadcasts my heart rate through Bluetooth and switching to it in my sports tracker took almost no effort. No more having to prepare my chest strap by wetting it before a run — that was a definite win.</p><p>Enough storytelling for now, let’s shift our focus back to the project. Like my old Sony smart band I bought second-hand, my Garmin Instinct 2 also broadcasts my heart rate on Bluetooth on demand. A quick search yielded <a href="https://github.com/kieranabrennan/blehrm">blehrm</a>, and it provides an abstraction to <a href="https://github.com/hbldh/bleak">bleak</a>. Unfortunately, it wasn’t the right library for the purpose, and I soon moved on to bleak directly after some failed attempts.</p><p>Firstly, we start by finding our device. Call the BleakScanner.discover method with a reasonable timeout, as shown below:</p><pre>from bleak import BleakScanner<br><br>ble_devices = await BleakScanner.discover(timeout=10.0)<br>print(f&quot;--- Discovered {len(ble_devices)} BLE Devices ---&quot;)<br>for i, device in enumerate(ble_devices):<br>    print(<br>        f&quot;#{i}: Name: {device.name}, Address: {device.address}, Details: {device}&quot;<br>    )</pre><p>Running that will return (device addresses are replaced with the placeholder &lt;address&gt;):</p><pre>--- Discovered 8 BLE Devices ---<br>#0: Name: Instinct 2, Address: &lt;address&gt;, Details: &lt;address&gt;: Instinct 2<br>#1: Name: None, Address: &lt;address&gt;, Details: &lt;address&gt;: None<br>#2: Name: None, Address: &lt;address&gt;, Details: &lt;address&gt;: None<br>#3: Name: U-WTD838C, Address: &lt;address&gt;, Details: &lt;address&gt;: U-WTD838C<br>#4: Name: None, Address: &lt;address&gt;, Details: &lt;address&gt;: None<br>#5: Name: None, Address: &lt;address&gt;, Details: &lt;address&gt;: None<br>#6: Name: None, Address: &lt;address&gt;, Details: &lt;address&gt;: None<br>#7: Name: None, Address: &lt;address&gt;, Details: &lt;address&gt;: None</pre><p>Jot down the address, as we will need it for the next step: establishing a connection to the device.</p><pre>from bleak import BleakClient<br><br>HR_MEASUREMENT_CHARACTERISTIC_UUID = &quot;00002a37-0000-1000-8000-00805f9b34fb&quot;<br>async with BleakClient(<br>    &lt;address&gt;,<br>    timeout=15.0<br>) as client:<br>    await client.start_notify(<br>        HR_MEASUREMENT_CHARACTERISTIC_UUID,<br>        heart_rate_handler,<br>    )</pre><p>In the snippet, we are sending the address we collected earlier to BleakClient with a reasonable timeout. Then we subscribe to the heart rate measurement event, and delegate the handling to a function.</p><p>With the help of Gemini, we saved time digging through the documentation, as it returned a ready-made snippet for the BLE connection and data parsing, which is shown below.</p><pre>def heart_rate_handler(sender, data):<br>    &quot;&quot;&quot;Callback to handle heart rate measurement data.&quot;&quot;&quot;<br>    # The heart rate data structure is defined in the BLE spec:<br>    # Byte 0: Flags (contains format of HR value and if other fields are present)<br>    # Byte 1: Heart Rate Value (8-bit or 16-bit)<br><br>    # Check the first bit of the flags to see if HR is 16-bit (0x01) or 8-bit (0x00)<br>    flags = data[0]<br>    is_16_bit = flags &amp; 0x01<br>    if is_16_bit:<br>        # 16-bit HR value is at index 1 and 2<br>        hr_value = unpack(&quot;&lt;H&quot;, data[1:3])[0]<br>    else:<br>        # 8-bit HR value is at index 1<br>        hr_value = data[1]<br>    logger.info(f&quot;[{flags:04b}] Heart Rate: {hr_value} BPM&quot;)</pre><p>There we have it, we have half the program done, and it is able to fetch heart rate data periodically from the device.</p><h3>Bridging the Gap: The Producer-Consumer Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iPoTtRyufsJY7PGx" /><figcaption>Photo by <a href="https://unsplash.com/@lenzil?utm_source=medium&amp;utm_medium=referral">Lenzil Gonsalves</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Continuing the story after I bought my second-hand Sony smart band. Electronics products die inevitably, as Sony wasn’t making a viable successor for the product I had to look elsewhere. That was when I first looked at Fitbit, particularly a Fitbit Charge 3. It was more than doubled the price of my smart band, though it came with more features. One feature I particularly liked was the sleep tracker, as I have really bad sleep pattern. It was working fine, though with a major drawback — I lost the ability to read my heart rate through the sports tracker app.</p><p>Since the device came with a screen itself, it did mean there was no need to whip out my phone constantly to check my heart rate. Not being able to log my run with heart rate data attached created a minor annoyance. On the other hand, I moved on to other sports already, namely boxing and weightlifting. The shift in activity did change the need as I didn’t need the data as often. For instance, the short-burst nature of weightlifting did not require constant monitoring of my heart rate; the main focus was just on whether I could lift the dumbbell or otherwise.</p><p>Again, the tracker died after serving for several years. I moved on to a Versa 3 on a good deal, despite the mild annoyance. Other brands were considered, but I got confused with the numerous lines of products and decided to stay with Fitbit for another time. Being a smart watch, Fitbit did release an SDK for their Versa watches, but they discontinued application development support when they released the successor, Versa 4. Regrettably, I didn’t put in the time and effort to develop anything as I was adequately happy with it.</p><p>As mentioned earlier, I found a way to broadcast my heart rate with an app offered in the Fitbit app store, and that led to the setup of a heart rate widget on my OBS setup. Coincidentally, I acquired Tetris Effect on my workstation, so I was curious to see if my heart rate changed throughout the game play. Surprisingly, it really did, and the recording clearly showed the heart rate fluctuations in action.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXtSY_DvsM-E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXtSY_DvsM-E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXtSY_DvsM-E%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/018de8b0f30246afd93165f500a77b62/href">https://medium.com/media/018de8b0f30246afd93165f500a77b62/href</a></iframe><p>Granted, as the tracker was worn on the wrist, the response was somewhat delayed. Despite that, the stream showed as the tetrimino dropped faster, my heart rate also increased correspondingly. More often than not, the height of dropped blocks waiting to be eliminated also played a role in influencing the heart rate.</p><p>Now that we have the stream of heart rate data, how do we recreate the widget in OBS through our script?</p><p>Open Broadcasting Studio, or OBS in short, offers a way to interact with the sources on screen through the websocket interface. In our case, we are interested in sending our heart rate data to a text source. By using the obsws-python library, we can send the data as soon as we capture it from the device. We can establish this connection to OBS using the following simple code:</p><pre>from obsws_python import ReqClient<br><br>obs = ReqClient(<br> host=&lt;host&gt;,<br> port=&lt;port&gt;,<br> password=&lt;password&gt;,<br>)</pre><p>All of these settings can be found in the OBS websocket setup page, as shown in the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smsVfNpsIrpHQrGgkfu8hg.png" /></figure><p>Sending heart rate to the source is simple, through the obs.set_input_settings method</p><pre>obs.set_input_settings(<br> &lt;identifier of the target source&gt;,<br> {“text”: f”{item:3d}”},<br> True,<br>)</pre><p>By assembling all these together we would have a complete program for the job. The only problem with putting everything together is that we are mixing asynchronous code calling bleak with a strictly synchronous and likely non thread-safe code by obsws-python. Fortunately, the data only flows one-way; otherwise it complicates the whole setup significantly more. Ideally the library that dealt with OBS websocket could be written in a more asynchronous manner but obsws-python was the only reliable library that I could find in a weekend.</p><p>The project started as a weekend project, and I stopped right after achieving a running proof-of-concept. Only later, when I finally had the time, did I start refactoring this into a more reliable program that properly handles errors and graceful shutdown. Considering we discussed rather extensively in the past on those topics, let’s skip to how we turn this into a producer-consumer design.</p><pre>with ThreadPoolExecutor(max_workers=5) as executor:<br>   executor.submit(producer)<br>   executor.submit(consumer)</pre><p>We want both the consumer and producer to remain isolated from each other, so we separate them into individual threads. Usually it is better to split them into different processes, but since we are only running one event loop for the producer part it is okay to stick with threads. In order to synchronize both of them, we need to pass a queue and an exit event to them as well. This can be achieved with functools.partial, or by writing a class with the dunder __call__ method, a topic we <a href="https://kitfucoda.medium.com/the-versatility-of-call-a-python-developers-secret-weapon-a6bff776971a">discussed previously</a>. I will leave the implementation detail out to focus on the core concept itself.</p><p>Now, back to our producer, where we collect the heart rate, instead of printing the heart rate, we dump it to our queue:</p><pre>logger.info(f”[{flags:04b}] Heart Rate: {hr_value} BPM”)<br>asyncio.create_task(asyncio.to_thread(queue.put, hr_value))</pre><p>In case you missed our series of <a href="https://kitfucoda.medium.com/concurrency-vs-parallelism-achieving-scalability-with-processpoolexecutor-c366bfcc6207">articles</a> on <a href="https://kitfucoda.medium.com/concurrency-vs-parallelism-achieving-scalability-with-processpoolexecutor-c366bfcc6207">AsyncIO</a> (go read them, they are awesome!), queue.put is a blocking operation, so we are delegating it to asyncio.to_thread. For our purpose, we don’t exactly care about the outcome, but we want to ensure it is scheduled safely. Therefore, we pass the returned coroutine object to asyncio.create_task.</p><p>On the other hand, as the code dealing with OBS is synchronous, we need to plan carefully.</p><pre>def consumer(queue: Queue, exit_event: Event) -&gt; None:<br>    obs = ReqClient(<br>        host=&lt;host&gt;,<br>        port=&lt;port&gt;,<br>        password=&lt;password&gt;,<br>    )<br><br>    logger.info(&quot;Starting consumption loop&quot;)<br>    while True:<br>        # task 1: handle the exit event<br>        if exit_event.is_set():<br>            logger.info(&quot;Exiting consumption loop&quot;)<br>            break<br><br>        # task 2: publish to obs<br>        with suppress(Empty):<br>            if item := queue.get(timeout=5.0):<br>                obs.set_input_settings(<br>                    &lt;identifier of the target source&gt;,<br>                    {&quot;text&quot;: f&quot;{item:3d}&quot;},<br>                    True,<br>                )</pre><p>This simplified snippet sets up an infinite loop that does two things, firstly it checks if the exit_event is triggered, and secondly, it consumes the heart rate data from the queue and sends it to OBS. We would need to set a timeout and suppress the potential Empty exception when getting a value from the queue. The reason for this is otherwise the code will block until it receives a data, and we would never be able to capture exit_event that was emitted elsewhere.</p><h3>Asyncio’s Role in Real-World, Non-Web I/O</h3><p>Essentially, this is a fairly common Consumer-Producer application between two different components. While the consumer is depending on the producer to publish to OBS, the producer should not have to wait for it to complete. By separating them into different threads and using a queue for synchronization, we allowed both components to work independently. Unlike the telegram chatbot we built previously, this shows how we can adapt synchronous code into an asynchronous environment.</p><p>I appreciate the fact that Garmin allows the heart rate data to be made available through an open interface. If I were to get a new Versa watch, this project would not have been possible as the data is locked away from a proprietary API. As mentioned earlier, Fitbit also removed support for application development for the newer models.</p><p>That would mean no more Tetris Effect streams with heart rate readings for me.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXSC61Y4UzwY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXSC61Y4UzwY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXSC61Y4UzwY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fd1166a20e17dcd450a99014354e282/href">https://medium.com/media/6fd1166a20e17dcd450a99014354e282/href</a></iframe><p>Not like anyone cared anyway.</p><p>So, is this project a good example as a response to the question posed early in the article? Is this a good demonstration of what asynchronous programming is capable of? I would argue yes, as this shows even though not all components are asynchronous, it is still possible to workaround it. When we have multiple components that need to talk to each other, asyncio is definitely a way to go, albeit requiring more thought and work into it.</p><p>That’s all I have for today! The code snippets are purposefully simplified for brevity, but if you are interested in the project, feel free to check it out on <a href="https://github.com/Jeffrey04/obs-garmin/">GitHub</a>. Thanks for reading, I shall see you in writing again soon.</p><p>For the sake of transparency, this article was a collaborative effort with my editor, Gemini, who assisted me throughout the writing process. Beyond providing editorial suggestions to tighten the narrative and structure, the model was instrumental in accelerating the technical side of the project, specifically by generating and verifying the initial code snippet required to correctly extract and parse the raw heart rate data from the BLE characteristic — a small but critical step that saved me hours of digging through specification sheets. The final code and the story are mine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=095db549d2fc" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/the-concurrency-choreographer-making-bles-async-data-sync-with-obs-095db549d2fc">The Concurrency Choreographer: Making BLE’s Async Data Sync with OBS</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Blog Post to PyCon: My One-Week Crash Course in Public Speaking]]></title>
            <link>https://python.plainenglish.io/from-blog-post-to-pycon-my-one-week-crash-course-in-public-speaking-ab4987b75702?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab4987b75702</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[introvert]]></category>
            <category><![CDATA[public-speaking]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 14:50:58 GMT</pubDate>
            <atom:updated>2025-11-12T18:13:16.720Z</atom:updated>
            <content:encoded><![CDATA[<p>If you were to deliver a talk in a conference for Ruby engineers, what would the topic be? That was a question I asked my supervisor during <a href="https://www.pycon.my/">PyCon MY</a> 2025. He eventually answered that he did not have a topic. Somehow it didn’t surprise me: a lot of incredible engineers I have met in life would likely respond similarly.</p><p>Including myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ICRD1xp8JUkEe9AmH54uUw.jpeg" /><figcaption>My name tag as a speaker</figcaption></figure><h3>Code vs. Conversation: The Socialization Problem</h3><p>My decision of submitting a talk likely raised a couple of eyebrows. Even my partner, Mr. H joked that I had brought the stress entirely upon myself whenever I complained about the preparation work. My former colleague even asked point-blank why I would make such a decision as an introvert. He added that he would not only avoid giving a talk, but he wouldn’t even consider attending the event.</p><p>Perhaps our lives take on a different trajectory, but in some ways, I see the ability to effectively communicate ideas being a part of the adulting or socialization process. For instance, I was once tasked with manning a booth in <a href="https://lalokalabs.co/en/2022/12/laloka-labs-at-the-innovate-tech-show-2022/">two different</a> <a href="https://lalokalabs.co/en/2022/12/attending-jomlaunch-2022/">trade shows</a> previously in another job. We were exposed to vastly different audiences when we were rotating between the two shows. As a result, the ability to explain the same concept in different contexts is crucial for people to relate to the company’s product.</p><ul><li><a href="https://lalokalabs.co/en/2022/12/laloka-labs-at-the-innovate-tech-show-2022/">LaLoka Labs at the iNNOVATE Tech Show 2022 - LaLoka Labs</a></li><li><a href="https://lalokalabs.co/en/2022/12/attending-jomlaunch-2022/">Attending JOMLAUNCH 2022 - LaLoka Labs</a></li></ul><p>To a certain extent, that experience alone piqued my interest to improve on my ability to communicate ideas. KitFu Coda, this very blog can be seen as a conscious effort for the purpose.</p><p>Just a few days ago, I realized this writing project started slightly over a year ago. Looking back, it expanded to different side ventures throughout the period, including a video, and just recently a talk. For the talk, the story started in late June, where a friend pinged in the community chatroom about the call for paper for the upcoming PyCon MY. With nudges from my mentor and fellow friends, I submitted my entries.</p><p>A few days after the submission, I coincidentally received a job offer. Between the new job and a series of family matters, I quickly forgot about the submission. That changed about two months ago when the approval for one of my submissions on AsyncIO hit my inbox. As I was still juggling between work and personal matters, I was somewhat relieved that my lightning talk on creating a DSL didn’t make it.</p><h3>From 20-Person Meetups to the Main Stage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_bKRpXZI-aAt4T2jjNa1g.png" /><figcaption>The title screen of my slide (Background is generated by Gemini)</figcaption></figure><p>Speaking of public speaking, I previously co-organized Rust Malaysia meetups, where I had the chance to share my learning journey and host workshop sessions. Most of the time I was dealing with a maximum of just 20 attendees. It is also worth noting that my last talk happened pre-COVID.</p><p>I can’t believe that was 5 years ago.</p><p>PyCon MY 2025 took place in Sunway University on the 1st and 2nd November. Compared to the meetups I ran, the difference in scale was massive. For instance, in my session I estimated there were at least a hundred attendees; that alone was enough to make me uncomfortable.</p><p>Preparation for the talk only started one week before the actual event. Due to the change of domain and tech stack at work and a series of family matters, my life only started to settle down fairly recently. Fortunately, we are living in an era where AI tools are getting increasingly helpful and easily accessible. This is a luxury my younger self wouldn’t have imagined. Naturally, given the tight timeframe due to my endless delay, I started by getting NotebookLM to generate an overview based on the source material.</p><p>The generated presentation was almost perfect that I jokingly told my peers that I felt useless.</p><p>After that, I turned to Gemini to start drafting the actual script for the presentation. Just as in my usual workflow, I planned the script as a storytelling project. While not perfect, the overview and initial draft did give me an idea of how to proceed.</p><p>Moving on, I needed to start preparing the slides. Considering the workshop-like nature, I decided to go with a simpler slide design and chose Google Slides. It still does the job fine; however, some of the controls were either moved to a new position or were completely replaced by the Gemini integration.</p><p>The final script was only done about two days before the presentation. I handwrote it on my tablet, as this method is proven to help with memorization. Later, during the dinner hosted by the organizer for speakers, one of the speakers mentioned how he only managed to complete his slides 10 minutes before his session. If I were in his shoes, I likely would have lost sleep in the days leading up to PyCon.</p><h3>Autopilot Engaged: The Crisis on Stage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiSNPbIORhJ6JOYuB67-Pg.jpeg" /><figcaption>Flustered me on stage (photo courtesy of PyCon MY)</figcaption></figure><p>Thinking back, my setup was likely overly complicated and hard to execute. My session was scheduled to be in the bigger auditorium hall. Unfortunately, it clashed with a talk by my project partner from SinarProject. Despite that, many showed up for the talk, and that amplified my uneasiness.</p><p>Ideally, I was supposed to have my timer on my phone, so as I went through my script on the tablet I would know how much time was left. Even with that seemingly perfect plan, juggling three devices at a time was almost impossible. I ended up forgetting to start the timer, and forgot about referring to the handwritten script, and just autopiloted through the presentation.</p><p>While I didn’t really keep track, I likely missed out a rough guesstimate of 40% of the content. On the other hand, I did put in effort to introduce only one idea in each slide so hopefully the core ideas are presented in a manageable pace.</p><p>If you are reading this and you attended the talk, feel free to reach out by commenting here for clarification.</p><h3>The Return: Why Just Showing Up Was the Answer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UffuxafzrserUD4Kyt1QA.jpeg" /><figcaption>If I can, you can too (photo courtesy of PyCon MY)</figcaption></figure><p>Attending PyCon as a speaker is indeed an interesting experience. While this is considered a smaller conference (my previous ones were PyCon APAC in KL and <a href="https://lalokalabs.co/en/2022/07/siang-attending-europython-2022/">EuroPython 2022</a> in Dublin, Ireland), I was considerably more stressed this time having to deliver a talk.</p><p><a href="https://lalokalabs.co/en/2022/07/siang-attending-europython-2022/">Siang attending EuroPython 2022 - LaLoka Labs</a></p><p>Until I am done with the talk, that is.</p><p>One of the reasons I like attending a conference or meetup is getting to know what people are working on. Apparently, quite a number of speakers are already adopting AsyncIO in their work, which made me wonder if my talk really mattered. This revelation does make me wonder about the people who showed up at my session. Were they just curious about the topic, or wanted to discover new use cases, or simply just there to validate their adoption to the feature?</p><p>Perhaps the choice of topic is a major consideration; however, the willingness to put oneself out there matters more. I can now appreciate the support my mentor offered when I was complaining about Rust adoption at work: he pushed me into organizing meetups. Sometimes, the act of standing out and yelling is what it takes to attract more feedback. In this case, speaking in a conference calls back to the problem I had when I started writing about AsyncIO — the constant need for shared knowledge on the topic.</p><p>Thanks again for joining me in this wonderful journey. I would like to take the opportunity to express my gratitude towards the organizers for hosting me, and putting in effort to maintain the friendly atmosphere. I shall write again, soon.</p><p>This article was developed with the editorial assistance of a large language model, Gemini. The model served as a linguistic and structural advisor, helping the author refine the grammar, correct flow issues, and polish the final prose. The core content, personal voice, and experiences remain the exclusive work of the author, Kitfucoda.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab4987b75702" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/from-blog-post-to-pycon-my-one-week-crash-course-in-public-speaking-ab4987b75702">From Blog Post to PyCon: My One-Week Crash Course in Public Speaking</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The && Fallacy: How --command Fixed VS Code Extensions in a Declarative Nix Shell]]></title>
            <link>https://blog.stackademic.com/the-fallacy-how-command-fixed-vs-code-extensions-in-a-declarative-nix-shell-1388eefa1f5e?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1388eefa1f5e</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[nix]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 10:22:50 GMT</pubDate>
            <atom:updated>2025-10-21T02:32:57.235Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://kitfucoda.medium.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59">In the last article</a>, we discussed the evolution of my development setup, focusing on how it became reproducible over time. It was originally written to document the process for my own amusement. Surprisingly, the stats tell a different story — apparently it resonated with enough people sharing the same pain. Over time, revisions were made alongside new discoveries, and I figured the journey was worth a retelling. Read on to find out about an unexpected milestone related to this very blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzOY6iSa5mArW2CikDQTDQ.png" /><figcaption>Cute illustration on the topic, by <a href="https://https//copilot.microsoft.com/">Microsoft Copilot</a></figcaption></figure><h3>The Editor’s Blind Spot: Nix vs. VS Code Extensions</h3><p>Up until the last article, we managed to get a rather consistent setup with home-manager to manage development tools, and subsequently <a href="https://kitfucoda.medium.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59">retired tools like </a><a href="https://kitfucoda.medium.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59">pyenv and </a><a href="https://kitfucoda.medium.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59">rbenv with the use of </a><a href="https://kitfucoda.medium.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59">nix-develop</a>. Little did I know, it wasn’t the end of the story. This time, we are tackling a new issue — the lack of nix-develop support of the Visual Studio Code extensions for development work in Ruby.</p><ul><li><a href="https://blog.stackademic.com/from-dotfile-hacks-to-open-source-my-development-environment-evolution-a771ea7bf8a8">From Dotfile Hacks to Open Source: My Development Environment Evolution</a></li><li><a href="https://blog.stackademic.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59">Beyond rbenv and pyenv: Achieving Reproducible Dev Setups with Nix</a></li></ul><p>Forcing the ruby-lsp extension to source an external Gemfile as detailed was a hackish solution. Although it worked for a bit, most of the time the extension failed to initialize the language server. Observing how inconsistent the behavior is, something must be wrong. On the other hand, setup seems impeccable, tests were passing, and projects were building fine too.</p><p>Unfortunately, not much luck with the team’s desired formatter.</p><p>It wouldn’t work in the editor.</p><p>A type checker extension called sorbet is also common, and that too wouldn’t work at all. Considering the team doesn’t type annotate the code, I quickly dismissed and deactivated the extension. Combining this with the previous problem where ruby-lsp failed to work, the itch grew as time passes on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fQ284dwYbjqK6d0B" /><figcaption>Photo by <a href="https://unsplash.com/@abusaeid01?utm_source=medium&amp;utm_medium=referral">Abu Saeid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Worse still, a formatter that doesn’t work at all times yields errors in the automated checks on every push.</p><p>Something was definitely wrong, was it because of VSCode failing to pick up the environment in a nix-develop session? My initial attempts to fix the flake file to include a command to <a href="https://github.com/Shopify/ruby-lsp/issues/1851">activate the language server properly as shared</a>. Still, none of them seemed to work reliably.</p><p><a href="https://github.com/Shopify/ruby-lsp/issues/1851">How To: Use vscode-ruby-lsp with flake.nix based dev enviroment · Issue #1851 · Shopify/ruby-lsp</a></p><p>After hitting walls enough times, I decided to post my setup to the discussion board to seek for help.</p><h3>The Log Line That Clicked Differently</h3><p>A problem can only be solved if we can clearly define it. We know the setup is failing, but what caused it? Interestingly enough, achieving the problem definition is a series of unlikely coincidences. It almost felt like solving a jigsaw puzzle, where each seemingly unrelated piece ultimately leads to the solution. So what are the missing pieces stalling our progress in understanding what went wrong?</p><p>Let’s start with the discovery of previously unused --command argument for nix-develop.</p><p>Initially, the gemini-generated flake file for the nix-develop sessions contained some commands to start my favorite fish shell. The snippet on starting a new shell was taken out from the previous discussion as it was somewhat unrelated. It was rather complicated and bound to fail because I was expecting it to work differently in different scenarios. Naturally, I wanted to simplify it somewhat, and eventually I learned about the --command argument.</p><p>Instead of relying on a clever (or dumb, depending on how you perceive it) detection logic, I could start a new fish shell session with</p><pre>nix develop /path/to/flake/dir --command fish</pre><p>Besides a shell, it could also run any command in the environment defined by the flake file. Discovering this was a crucial step toward fixing the launch of the ruby-lsp language server in the editor.</p><p>Remember I posted <a href="https://github.com/Shopify/ruby-lsp/discussions/3683">an SOS message on the discussion board</a>? Luckily, it caught the attention of <a href="https://vinistock.com/">Vinicius Stock</a>, the project owner. Helpfully enough, he pointed out that an external Gemfile is not necessary, and asked me to check if the language server is launched properly. With that, I checked the log and found this line</p><pre>2025-07-27 16:56:30.669 [info] (ship_it) Running command: `nix develop /Users/jeffrey04/Projects/home-manager/devenvs/ruby-3.3 &amp;&amp; ruby -EUTF-8:UTF-8 &#39;/Users/jeffrey04/.vscode-oss/extensions/shopify.ruby-lsp-0.9.31/activation.rb&#39;` in /Users/jeffrey04/Projects/ship_it using shell: /Users/jeffrey04/.nix-profile/bin/bash</pre><p>Despite seeing the log multiple times before, now that I know about the --command argument, the same line clicked differently. Does the ruby command after the &amp;&amp; operator run in the nix-develop session? Validating in this case is rather easy, just run</p><pre>nix develop /path/to/flake/dir &amp;&amp; ruby --version</pre><p>Oops, why am I being dropped to a new shell session? Let me exit the session, and sure enough, the ruby command refers to the version offered by the operating system.</p><pre>❯ nix develop ~/Projects/home-manager/devenvs/ruby-3.3 &amp;&amp; ruby --version<br>warning: updating lock file &quot;/Users/jeffrey04/Projects/home-manager/devenvs/ruby-3.3/flake.lock&quot;:<br>• Added input &#39;nixpkgs&#39;:<br>    &#39;github:NixOS/nixpkgs/544961dfcce86422ba200ed9a0b00dd4b1486ec5?narHash=sha256-EVAqOteLBFmd7pKkb0%2BFIUyzTF61VKi7YmvP1tw4nEw%3D&#39; (2025-10-15)<br>(nix:ruby-3.3-env) wukong:ib-vpn jeffrey04$<br>exit<br>ruby 2.6.10p210 (2022-04-12 revision 67958) [universal.x86_64-darwin24]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jSpPmgyc2V98iFRo" /><figcaption>Photo by <a href="https://unsplash.com/@matiasmalka?utm_source=medium&amp;utm_medium=referral">Matias Malka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Clearly, the assumption that the command following the &amp;&amp; operator is flawed from the very beginning. With this revelation, we can finally define what the problem is — the language server is not properly launched. In this case, all we need to do is to replace the boolean AND operator into --command.</p><p>Easy to say, but implementation is a challenge for someone who has no experience with vscode extension development like myself.</p><p>And this is exactly when <a href="https://kitfucoda.medium.com/vibe-coding-storytelling-and-llms-a-collaborative-approach-db5e9a62c8b1">vibe-coding is useful</a>, with a clear problem definition and goal, the solution was just a prompt or two away with the help of gemini-cli. As expected, the patch worked flawlessly.</p><p>Firstly, add a new enum entry to ManagerIdentifier in vscode/src/ruby.ts</p><pre>export enum ManagerIdentifier {<br>  Asdf = &quot;asdf&quot;,<br>  Auto = &quot;auto&quot;,<br>  Chruby = &quot;chruby&quot;,<br>  Rbenv = &quot;rbenv&quot;,<br>  Rvm = &quot;rvm&quot;,<br>  Shadowenv = &quot;shadowenv&quot;,<br>  Mise = &quot;mise&quot;,<br>  RubyInstaller = &quot;rubyInstaller&quot;,<br>  NixDevelop = &quot;nix-develop&quot;, # add this line<br>  None = &quot;none&quot;,<br>  Custom = &quot;custom&quot;,<br>}</pre><p>Then a new case in the runManagerActivation method</p><pre>case ManagerIdentifier.NixDevelop:<br>  await this.runActivation(<br>    new NixDevelop(this.workspaceFolder, this.outputChannel, this.context, this.manuallySelectRuby.bind(this)),<br>  );<br>  break;</pre><p>Followed by a new module at vscode/src/ruby/nixDevelop.ts that contains the activation logic:</p><pre>import * as vscode from &quot;vscode&quot;;<br><br>import { VersionManager, ActivationResult } from &quot;./versionManager&quot;;<br><br>export class NixDevelop extends VersionManager {<br>  async activate(): Promise&lt;ActivationResult&gt; {<br>    const customCommand = this.customCommand();<br>    const command = `nix develop ${customCommand} --command ruby`;<br>    const parsedResult = await this.runEnvActivationScript(command);<br><br>    return {<br>      env: { ...process.env, ...parsedResult.env },<br>      yjit: parsedResult.yjit,<br>      version: parsedResult.version,<br>      gemPath: parsedResult.gemPath,<br>    };<br>  }<br><br>  private customCommand() {<br>    const configuration = vscode.workspace.getConfiguration(&quot;rubyLsp&quot;);<br>    const customCommand: string | undefined =<br>      configuration.get(&quot;customRubyCommand&quot;);<br><br>    return customCommand || &quot;&quot;;<br>  }<br>}</pre><p>Lastly, enable the option forrubyVersionManager in vscode/package.json</p><pre>        &quot;rubyLsp.rubyVersionManager&quot;: {<br>          &quot;type&quot;: &quot;object&quot;,<br>          &quot;properties&quot;: {<br>            &quot;identifier&quot;: {<br>              &quot;description&quot;: &quot;The Ruby version manager to use&quot;,<br>              &quot;type&quot;: &quot;string&quot;,<br>              &quot;enum&quot;: [<br>                &quot;asdf&quot;,<br>                &quot;auto&quot;,<br>                &quot;chruby&quot;,<br>                &quot;none&quot;,<br>                &quot;rbenv&quot;,<br>                &quot;rvm&quot;,<br>                &quot;shadowenv&quot;,<br>                &quot;mise&quot;,<br>                &quot;nix-develop&quot;, // add this line<br>                &quot;custom&quot;<br>              ],</pre><p>Don’t forget about the actual config (omit the rubyLsp.customRubyCommand if flake.nix is in the workspace)</p><pre>&quot;rubyLsp.rubyVersionManager&quot;: {<br>    &quot;identifier&quot;: &quot;nix-develop&quot;<br>},<br>&quot;rubyLsp.customRubyCommand&quot;: &quot;/Users/jeffrey04/Projects/home-manager/devenvs/ruby-3.3&quot;,</pre><p>The patch is definitely not perfect, and it is reusing the optional customRubyCommand configuration item to define where the directory containing the flake file is. Yet, considering this likely affects only a small group of users, I don’t see a need to introduce a new configuration field for the purpose. Contributions are definitely welcome at the <a href="https://github.com/Shopify/ruby-lsp/pull/3691">submitted pull request</a>, as it has been stalling for months.</p><p>For the sorbet part, I managed to get it working one day out of boredom. Most of the Ruby code I have access for now is not type-annotated, so the effort is purely for fun. A quick and dirty way to do so, is building the language server application directly, and configure vscode as follows</p><pre>&quot;sorbet.enabled&quot;: true,<br>&quot;sorbet.selectedLspConfigId&quot;: &quot;without-bundler&quot;,<br>&quot;sorbet.userLspConfigs&quot;: [<br>    {<br>        &quot;id&quot;: &quot;without-bundler&quot;,<br>        &quot;name&quot;: &quot;sorbet&quot;,<br>        &quot;description&quot;: &quot;Launch locally compiled sorbet&quot;,<br>        &quot;command&quot;: [&quot;/path/to/sorbet&quot;, &quot;typecheck&quot;, &quot;--lsp&quot;, &quot;--dir=/path/to/project&quot;]<br>    }<br>]</pre><p>For some reason I needed to --disable-watchman flag in the command too, but as there’s no real need for now I am not going to dig further.</p><p>There you have it, with simplified flake files (removing the detection logic to start fish shell) and invoking fish shell explicitly with --command, and patches and hacks to enable the ruby toolings, we finally have a functional setup for development work in Ruby. Seeing the pull request being stalled for months (and their bot closed my PR recently due to inactivity) does make me upset for a little bit. Moving forward I may need to consider maintaining a fork for it as it does affect my work.</p><h3>Stalled PR, Sudden Payoff: The Two Timelines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cP36WVy-iKsY5dMX" /><figcaption>Photo by <a href="https://unsplash.com/@enginakyurt?utm_source=medium&amp;utm_medium=referral">engin akyurt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Patches to the ruby-lsp were submitted in the late July, and I was hoping to start drafting this article when it received a review. Unfortunately, that didn’t happen. I was caught up with my new job and several major family issues while waiting on the PR. Things finally settled down for a little bit, and I should be back to a relatively more predictable routine. Hopefully this translates to a more consistent publishing schedule for <a href="https://kitfucoda.medium.com/">KitFu Coda</a>.</p><p>As for the unexpected milestone teased in the beginning, it is about a talk I am about to deliver during the upcoming <a href="https://www.pycon.my/">PyCon Malaysia</a>. My mentor encouraged me to submit for the CFP and <a href="https://cfp.pycon.my/pyconmy-2025/talk/review/LNN8WWYV93JYTKZMEGKE79KBWJM73J8M">it somehow went through</a>. If you are interested in applying AsyncIO in projects, do feel free to drop by and say Hi. For reference, it is based on the articles I published earlier, as linked below.</p><ul><li><a href="https://kitfucoda.medium.com/understanding-awaitables-coroutines-tasks-and-futures-in-python-a9c12890d20d">Understanding Awaitables: Coroutines, Tasks, and Futures in Python</a></li><li><a href="https://kitfucoda.medium.com/asyncio-task-management-a-hands-on-scheduler-project-bd7b7fe58c7e">AsyncIO Task Management: A Hands-On Scheduler Project</a></li><li><a href="https://kitfucoda.medium.com/concurrency-vs-parallelism-achieving-scalability-with-processpoolexecutor-c366bfcc6207">Concurrency vs. Parallelism: Achieving Scalability with ProcessPoolExecutor</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FC9kfkMBAMSLZhwE" /><figcaption>My talk, come say Hi! Image credit <a href="https://www.instagram.com/p/DQDaTeTDwjD/">Pycon My</a></figcaption></figure><p>I also discussed briefly with my supervisor in one of our 1 on 1 sessions, mainly to check on any necessary approvals or conflict of interest. He was incredibly supportive about it and offered some tips on presenting ideas to a wider audience. As I am new to Ruby, he also briefly explained how the language approaches asynchronous programming. On a lighter note, he’s even been checking on my preparation progress (zero so far), especially in recent sessions!</p><p>With this article checked off in my TODO, I can finally allocate some time on the preparation work. I sometimes feel like I’m running on an energy tank whose maximum capacity depletes as we age. These days, even finding time to game is a challenge. I feel bad for my character in <em>Xenoblade X</em> and I wonder if I’ll ever have time for the new <em>Pokémon Legends Z-A</em> game I’m about to purchase.</p><p>Finally, I would like to thank everyone for the support, especially to everyone who reads my work here. Though I have not been publishing much, since starting this technical writing project opens up fascinating new opportunities. Besides scoring a new job, I also started exploring scripted video making, and now a talk. I am thankful and hope to inspire more people through this trying time.</p><p>Thanks again for reading, I shall write again soon.</p><p>Throughout this journey, Gemini served as a valuable editorial companion, helping refine my prose. However, the voice and code remain entirely my own. I welcome your feedback and recommendations in the comments below, and invite you to subscribe to my <a href="https://kitfucoda.medium.com/">Medium</a> for more content on my development adventures!</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1388eefa1f5e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-fallacy-how-command-fixed-vs-code-extensions-in-a-declarative-nix-shell-1388eefa1f5e">The &amp;&amp; Fallacy: How --command Fixed VS Code Extensions in a Declarative Nix Shell</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond rbenv and pyenv: Achieving Reproducible Dev Setups with Nix]]></title>
            <link>https://blog.stackademic.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/04b610175a59</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[nix]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 07:53:10 GMT</pubDate>
            <atom:updated>2025-07-21T12:16:13.997Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up a development environment is a painful process, as I <a href="https://kitfucoda.medium.com/from-dotfile-hacks-to-open-source-my-development-environment-evolution-a771ea7bf8a8">discussed previously</a> when detailing how mine evolved to the combination of home-manager and Ubuntu Make. Little did I know, the article gained significant traction and likely resonated with many fellow developers. Coincidentally, I got into a new job earlier in the month, and this necessitated a revision to the setup on a MacOS environment. How did it go? Turbulent would be an appropriate adjective to describe the whole experience, as you may expect.</p><p><a href="https://blog.stackademic.com/from-dotfile-hacks-to-open-source-my-development-environment-evolution-a771ea7bf8a8">From Dotfile Hacks to Open Source: My Development Environment Evolution</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t17Pg0TlocDfGtPxS8To3A.png" /><figcaption>A cute illustration from <a href="https://copilot.microsoft.com/">Copilot</a></figcaption></figure><h3>The macOS Catalyst: A New Job, A New Challenge</h3><p>Replicating a development setup over multiple machines can be a hard problem, and ensuring it works on different operating systems significantly increases that complexity. As we delve deeper into the topic, you will see how I shoot myself in the foot repeatedly, and the corresponding steps to recover.</p><p>Why a Mac?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9L-vGU5dIoVaFnew" /><figcaption>Photo by <a href="https://unsplash.com/@purzlbaum?utm_source=medium&amp;utm_medium=referral">Claudio Schwarz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before starting my new role, I was asked if I would prefer a Linux machine or a Mac for work. Though I am relatively comfortable with a Linux machine, I picked Mac as I reckoned it is easier to get enterprise apps whenever necessary. I also reiterated this same reason when my coworker and I were pairing up for a task.</p><p>Despite working mostly with Ubuntu, I do have a Intel iMac for video calls and functioning as a second screen for documentation and web project previews. A minimal home-manager setup worked mostly fine, and I assumed expansion of the setup for development would be as painless.</p><p>Oh, how wrong I was.</p><p>As the assigned MacBook Pro became my primary device for work, all the minor problems surfaced. First, my shells were not initialized properly in the terminal emulator. After getting that fixed, I got adventurous and decided to retire rbenv to manage Ruby versions. Coupled with the struggle to set up my code editor, I was amazed how my feet survived all the gunshots.</p><h3>Diving into the Rabbit Holes: macOS and Interpreter Woes</h3><p>How hard can it be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i3phby67nWZBNKAX" /><figcaption>Photo by <a href="https://unsplash.com/@nachristos?utm_source=medium&amp;utm_medium=referral">Nachristos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If one is looking for a statement to best represent underestimation, that would be it. Looking back, the problems look very trivial, but each was a great learning opportunity. Hang on tight, as we are going into a deep dive into all the rabbit holes I fell into with the revised setup, and to learn how to overcome them.</p><p>Compared to Windows, macOS offers a more familiar environment for developers with experience in Linux. We can interact with the system through a similar command-line interface. With a package manager, we can even add different shells not shipped with the operating system, like my favourite <a href="https://fishshell.com/">fish shell</a>. Trying to configure an iTerm2 profile for fish is exactly the first hole I fell into.</p><p>Why would macOS not source .profile in a graphical session?</p><p>Unlike Ubuntu, macOS <a href="https://ghostty.org/docs/help/macos-login-shells">does not source </a><a href="https://ghostty.org/docs/help/macos-login-shells">.profile in a graphical session</a>. Most of the time, the script updates the PATH variable, making locally installed applications discoverable. Subsequently, shell initialization scripts (like .bashrc for bash and config.fish for fish) then set up individual application based on the environment defined in .profile.</p><p>Multiple variations was attempted, until I stumbled upon <a href="https://superuser.com/questions/446925/re-use-profile-for-fish">a Q&amp;A on superuser</a>. Thinking it would be useful, I sent the proposed answer to Gemini and asked if it would be applicable for my case. Turns out I only needed a little tweak.</p><pre>/bin/sh -lc &quot;exec -l /path/to/fish&quot;</pre><p>This is a breakdown of the command:</p><ol><li>/bin/sh: This specifies that the command should be executed by the Bourne shell, launching a new instance of this basic shell.</li><li>/bin/sh -l: this tells the shell to launch as a login shell, ensuring it sources standard login files like .profile.</li><li>/bin/sh -c: This tells the shell to execute the command provided in the string that follows.</li><li>exec: This <a href="https://devconnected.com/understanding-processes-on-linux/#Execute_operation">crucial command</a> tells the shell to replace the current /bin/sh process with a new process (in this specific case, the fish shell).</li><li>exec -l: This tells the new shell (e.g., fish) to launch as a login shell itself.</li><li>/path/to/fish: This is the full path to your fish shell executable. With the -l flag in the exec command, this fish shell will then source its own login initialization configuration file (e.g., config.fish).</li></ol><p>Similarly, the command can be adapted to work with byobu, my preferred terminal multiplexer. The -l flag is omitted for the exec command as byobu is not a shell.</p><pre>/bin/sh -lc &quot;exec /path/to/byobu new-session&quot;</pre><p>For completeness’ sake, the setup for a bash profile is a lot simpler, as it sources .profile and .bashrc properly when launched as a login shell -l itself.</p><pre>/path/to/bash -l</pre><p>What a ride.</p><p>Shifting from Python to Ruby as my main development language presented an opportunity to review the toolings involved. Previously I relied on pyenv to provide isolated Python interpreters for individual projects. Eventually, the functionality was replaced by uv, which also manages pre-built CPython distributions as well. Unfortunately, I wasn’t aware of an alternative for Ruby, and had to continue relying on rbenv for the purpose.</p><p>One of the main goals of using home-manager, as discussed in the previous article, was to achieve idempotency and to isolate dev packages from the system package manager (such as apt in Ubuntu). Thus, we need to first define the packages in the home-manager flake file, as shown below:</p><pre>packages = with pkgs; [<br>    ...<br>    # dev libraries<br>    openssl<br>    zlib-ng<br>    bzip2<br>    readline<br>    sqlite<br>    ncurses<br>    xz<br>    tcl<br>    tk<br>    xml2<br>    xmlsec<br>    libffi<br>    libtool<br>    libyaml<br>    libxml2<br>    libxslt<br>  ];</pre><p>Essentially, this yields an isolated filesystem namespace that is unrecognized by the operating system. In order to get the compiler to utilize the pulled development package, we need to tell `rbenv` where to look for them, as shown in the shell script below:</p><pre>#!/usr/bin/env sh<br><br>export CPPFLAGS=&quot;-I$HOME/.nix-profile/include $CPPFLAGS&quot;<br>export CFLAGS=&quot;-I$HOME/.nix-profile/include $CFLAGS&quot;<br>export LDFLAGS=&quot;-L$HOME/.nix-profile/lib $LDFLAGS&quot;<br>export PKG_CONFIG_PATH=$HOME/.nix-profile/lib/pkgconfig:$HOME/.nix-profile/share/pkgconfig:$PKG_CONFIG_PATH<br>export C_INCLUDE_PATH=$HOME/.nix-profile/include:$C_INCLUDE_PATH<br>export INCLUDE_PATH=$HOME/.nix-profile/include:$INCLUDE_PATH<br>export LIBRARY_PATH=$HOME/.nix-profile/lib:$LIBRARY_PATH<br>export LD_LIBRARY_PATH=$HOME/.nix-profile/lib:$LD_LIBRARY_PATH<br><br>$HOME/.nix-profile/bin/rbenv install -vf 3.3.5</pre><p>It worked fine, though I always found this a dirty hack, as it required explicitly defining the flags and include paths. There has to be a better way.</p><h3>The Nix Pivot: Discovering a Declarative Path</h3><p>If not rbenv, then how do we approach Ruby version management? Turns out we can use another feature provided by Nix to build a development environment through a declarative manner. So how is this relevant to the problem we are looking at though?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uqrvCw46GE479P0z" /><figcaption>Photo by <a href="https://unsplash.com/@randobrando02?utm_source=medium&amp;utm_medium=referral">Jonathon B. Carreño</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A friend of mine had been hinting for a while that I could completely replace rbenv with Nix but I didn’t explore deeper. That changed when I saw the announcement of the gemini-cli app. In the installation guide, it called for npx, but the tool was not available as a Nix package. After some exchanges with Gemini, it suggested I look into nix shell, and the conversation quickly evolved into an introductory session on nix develop.</p><p>Just a side note, gemini-cli was already packaged not long after the announcement, no need for npx. If I were to follow the installation guide, npx could be made available through a nix shell -p nodejs session. In case you missed how this could be related to our original problem, the equivalent for Ruby would be nix shell -p ruby.</p><p>What if I need to install gems that require some special dev libraries?</p><p>You just unlocked the reason the conversation turned into an introduction to nix develop. Like home-manager, the input for the command is a flake file, written in the Nix programming language, declaring the development environment setup. Naturally, this added complexity made me hesitant to commit to this strategy. I was still trying to get more comfortable with home-manager and wanted to take more conservative baby steps in adopting additional features offered by Nix.</p><p>Essentially, there are two important components to be declared in the flake: the list of packages and an initialization shell script. For example, we can define a development environment sporting Ruby 3.3 with the list of packages like so:</p><pre>buildInputs = with pkgs; [<br>  # fish is kept so that fish-specific completions from<br>  # packages can be made available.<br>  fish<br>  # Git is needed for fetching gems from git repositorie<br>  git<br>  # The Ruby interpreter (3.3.8 as the time of writing)<br>  ruby<br>  # Bundler for managing Ruby gems.<br>  bundler<br>  # Common dependencies for building native extensions.<br>  cmake<br>  gcc<br>  gnumake<br>  # Libraries often required by gems.<br>  openssl<br>  pkg-config<br>  libmysqlclient<br>  shared-mime-info<br>  re2<br>  readline<br>  zlib<br>] ++ lib.optionals stdenv.isDarwin [<br>  # Add macOS-specific dependencies.<br>  libiconv<br>];</pre><p>Secondly, the initialization script definition</p><pre>shellHook = &#39;&#39;<br>  # Ruby-specific setup<br>  export FREEDESKTOP_MIME_TYPES_PATH=&quot;${pkgs.shared-mime-info}/share/mime/packages/freedesktop.org.xml&quot;<br><br>  echo &quot;Ruby dev environment activated for ${system}!&quot;<br>&#39;&#39;;</pre><p>Incorporating these into the flake file makes nix develop a superior method to set up a development environment. Compared to just listing packages in nix shell, the shellHook component allows more control and further manipulation, enabling us to set up proper environment variables and run initialization commands. Additionally, the declarative nature of a flake file also means it is highly reproducible and can be easily shared.</p><h3>A Harmonious Setup: Validation and Reflection</h3><p>Remember I needed to redefine library path and compiler flags to compile Ruby interpreters? That problem eventually came back while I was installing gems for work projects. Long story short, I gave in and adopted nix develop. Does it work out of the box? Does the adoption of nix develop stop me from shooting myself in the foot?</p><p>In order to be cautious, I replicated and adapted the flake for my bigmeow side project, which is still managed by Poetry, and hence relied on pyenv. Fortunately, a satisfactory outcome was achieved after a few iterations. On the other hand, direnv also offers some integration with nix develop. Automated activation of a development environment can be achieved by adding one line to the respective .envrc:</p><pre>use flake /path/to/folder # the folder that contains the flake.nix declaration</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*axJYZtjNEhYB998Q" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Applying the Ruby counterpart also went rather smoothly. There were some problems in the earlier iterations, but they were mostly trivial, and all it took was a regeneration by Gemini. Compared to the relatively smooth sailing in environment setup, taming my code editor to work with it was a lot more frustrating.</p><p>In recent years, most extensions bridging the code and development tools would often bundle the tool together. For instance, if I install an extension to format Python code with ruff formatter in Visual Studio Code, it would bundle ruff itself in the package. This saves the developer from needing to declare ruff as a dependency of the project.</p><p>Likely due to the highly modular design, the experience was a lot more complicated in the Ruby world. One of my work projects defined an ancient version of the Rubocop formatter, and none of the editor extensions offered in the marketplace would work with it. Forcing the extension to use the bundled gem would fail, because it wouldn’t work with the equally outdated rubocop extension gems (rubocop-rails, rubocop-minitest) installed in the project.</p><p>Updating the lock file is not a practical solution and I was stuck there for a while. Thankfully a coworker shared that I could explore the <a href="https://github.com/Shopify/ruby-lsp">ruby-lsp extension</a>. Apparently, this extension makes it possible to refer to an alternative Gemfile, i.e. I could have a Gemfile for all the development tools saved outside of the project. In this particular case, I could have a Gemfile like this</p><pre>source &quot;https://rubygems.org&quot;<br><br>gem &quot;ruby-lsp&quot;<br>gem &quot;rubocop&quot;, &quot;1.26.1&quot;<br>gem &quot;rubocop-rails&quot;<br>gem &quot;rubocop-minitest&quot;</pre><p>Solving that yields an functional setup that I was happy enough for work. Looking back, everything seemed rather trivial, but in reality I was stuck for a couple of days. Despite the added complexity, getting all these parts working together felt like putting together puzzle pieces. Getting them configured correctly is giving the same satisfaction as solving a complex jigsaw puzzle.</p><p>Is this increased complexity worth the effort? Would there be a better alternative strategy out there? I am curious to know about them and am open to recommendations and corrections. Meanwhile, I do find the revision to retire version managers a fruitful learning experience. Another part I liked about the current implementation is the elimination of explicit declaration of dev packages to build the interpreters. If you ask me, I would say replacing the version managers and removing dev packages for interpreter compilation with nix develop flake files is totally worth the effort.</p><p>Throughout this journey, Gemini served as a valuable editorial companion, helping refine my prose. However, the voice and code remain entirely my own. I welcome your feedback and recommendations in the comments below, and invite you to subscribe to my <a href="https://kitfucoda.medium.com/">Medium</a> for more content on my development adventures!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04b610175a59" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/beyond-rbenv-and-pyenv-achieving-reproducible-dev-setups-with-nix-04b610175a59">Beyond rbenv and pyenv: Achieving Reproducible Dev Setups with Nix</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Pygame Framework I Didn’t Plan: Building Tic-Tac-Toe with Asyncio and Events]]></title>
            <link>https://python.plainenglish.io/the-pygame-framework-i-didnt-plan-building-tic-tac-toe-with-asyncio-and-events-ea7ed54ec705?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea7ed54ec705</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pygame]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 13:11:26 GMT</pubDate>
            <atom:updated>2025-07-06T01:53:04.018Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last weekend, I spent some time mucking around with <a href="https://www.pygame.org/news">Pygame</a>. Despite facing some challenges along the way, I ended up with a working prototype. There was neither design nor specification drafted for the project. Nonetheless, mid-development, a reusable design emerged, and we discussed that in last week’s article. Following that discovery, we will explore the implementation this week and answer the question ‚ “Can we make a framework out of it?”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFBQUlLgruEaJ-xBPLUYCQ.png" /><figcaption>Cute illustration from <a href="https://copilot.microsoft.com/">Copilot</a></figcaption></figure><h3>The Unexpected Framework: From Pygame Hacks to a Reusable Design</h3><p><a href="https://kitfucoda.medium.com/understanding-awaitables-coroutines-tasks-and-futures-in-python-a9c12890d20d">Understanding Awaitables: Coroutines, Tasks, and Futures in Python</a></p><p>As a brief recap to the <a href="https://kitfucoda.medium.com/my-pygame-evolution-embracing-asyncio-and-immutability-for-scalable-design-84eae4601717">last article</a>, we know how Pygame is designed to be primitive, and lacks inherent structure. Building a Pygame application would therefore require a developer to begin by writing the main application loop. On the other hand, this also presents an opportunity to design a bespoke structure for graphical application development. By refactoring our work from last week, we will witness how a framework emerges, while adhering the original design goal to stay immutable and reliable.</p><p>Adapting the synchronous main application loop to AsyncIO took quite some effort. Despite the complexity involved, it was worth it because it broke the tight coupling of display update and event dispatching loop. Previously, events were only fetched once per display update cycle. If the application was written in a pure event driven manner, delegating work into multiple events would introduce latency.</p><p>Now that both event dispatching and display update run independently, ensuring synchronization of application states between the two components is also crucial. Immutability was therefore introduced such that application data can only be changed through publishing changes to relevant queues.</p><p>With all the work laid out, this opens up an interesting potential, allowing the orchestration code for event dispatching and display updates to be split from the game logic. Application setup work, such as event handler registrations and the initialization of application-specific data, is the primary area that differs from one application to another.</p><p>Sounds like a plan, let’s split it out, and complete the tic-tac-toe game we started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZM4TOBEllAcdECvK" /><figcaption>Photo by <a href="https://unsplash.com/@d_mccullough?utm_source=medium&amp;utm_medium=referral">Daniel McCullough</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Building the Core: Immutable State and Asynchronous Orchestration</h3><p>It shouldn’t be difficult, right? Given the design goal mentioned earlier, the splitting work was indeed not too difficult. On the other hand, keeping track of the declared dataclasses is another story. Regardless, we will uncover an architectural pattern that forms the framework core through some refactoring work. Some minor revisions will be made to the state management, as well as the main application loop. All this work yields a reusable framework for simple graphical applications.</p><p>Previously we were creating multiple queues for different fields in our Application dataclass. Having multiple queues serving similar purpose to update values is fine, though I personally find it wasteful. Why not just consolidate them?</p><p>And I did exactly that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pbPfF-uj2A66b_aR" /><figcaption>Photo by <a href="https://unsplash.com/@usgs?utm_source=medium&amp;utm_medium=referral">USGS</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Firstly, we start by introducing an Enum to represent the field we intend to update</p><pre>class ApplicationDataField(Enum):<br>    STATE = auto()<br>    ELEMENTS = auto()<br>    EVENTS = auto()</pre><p>Secondly, we update the DeltaOperation to always require the field we intend to update</p><pre>@dataclass<br>class DeltaOperation(ABC):<br>    field: ApplicationDataField<br>    item: Any</pre><p>Lastly, we need to update the application_refresh function, which is the only place where the Application object is updated throughout the framework.</p><pre>async def application_refresh(application: Application) -&gt; Application:<br>    result = application<br><br>    with suppress(asyncio.queues.QueueEmpty):<br>        while delta := application.delta_data.get_nowait():<br>            field = application_get_field(application, delta.field)<br><br>            match delta:<br>                case DeltaAdd():<br>                    result = replace(<br>                        result,<br>                        **{field: getattr(result, field) + (delta.item,)},<br>                    )<br><br>                case DeltaUpdate():<br>                    result = replace(<br>                        result,<br>                        **{<br>                            field: tuple(<br>                                delta.new if item == delta.item else item<br>                                for item in getattr(result, field)<br>                            )<br>                        },<br>                    )<br><br>                case DeltaDelete():<br>                    result = replace(<br>                        result,<br>                        **{<br>                            field: tuple(<br>                                item<br>                                for item in getattr(result, field)<br>                                if not item == delta.item<br>                            )<br>                        },<br>                    )<br><br>    return result</pre><p>Actual implementation is a little bit longer, but I truncated for brevity. Logically, the current version is rather similar to the previous version, though it only consumes from one single queue (application.delta_data) to update the states in an Application object.</p><p>After the minor refactoring to the state management, we shift our attention to the main application loop.</p><pre>async def main_loop(<br>    application_setup: Awaitable[Application],<br>) -&gt; None:<br>    pygame.init()<br><br>    application = await application_setup<br><br>    pygame.event.post(pygame.event.Event(SystemEvent.INIT.value))<br><br>    tasks = []<br><br>    tasks.append(<br>        asyncio.create_task(<br>            display_update(<br>                application.delta_screen,<br>                application.clock,<br>            )<br>        )<br>    )<br>    tasks.append(<br>        asyncio.create_task(events_process(application))<br>    )<br><br>    await application.exit_event.wait()<br><br>    pygame.quit()</pre><p>It is almost similar to the original run function in our original code, with just 2 small changes. Remember I mentioned about wanting a window.onload like system events? Here we are emitting an INIT event before we start the display update and event dispatching loops. Additionally, setup code is passed in as <a href="https://medium.com/p/ea7ed54ec705/edit">an </a><a href="https://medium.com/p/ea7ed54ec705/edit">Awaitable object</a>, that is only scheduled to run after pygame.init().</p><p><a href="https://kitfucoda.medium.com/understanding-awaitables-coroutines-tasks-and-futures-in-python-a9c12890d20d">Understanding Awaitables: Coroutines, Tasks, and Futures in Python</a></p><p>That’s practically it, though extracting them out to another module, is a pain due to how these functions reference numerous dataclasses and other helpers. Alongside these changes, I also added some helpers to deal with in-game state management. Spiritually, the design of these helper functions loosely follows <a href="https://redux.js.org/">Redux</a>, though the implementation is a lot simpler in my implementation. We shall see them in action when we go through the game implementation next.</p><h3>Framework in Action: Bringing Tic-Tac-Toe to Life</h3><p>Framework is now done, what’s next?</p><p>What’s a better way to test the framework, than building a game for real? Now that we delegate the orchestration work to another module, we can now focus purely on the game logic. Throughout the discussion, we can observe how the framework design enables building of a simple game with just dispatching events and implementing the handlers. Game state management as mentioned earlier will be discussed as well.</p><p>Firstly, let’s set-up the game:</p><pre>async def setup() -&gt; Application:<br>    application = Application(screen=pygame.display.set_mode((300, 300)))<br>    application = await add_event_listeners(<br>        application,<br>        (<br>            (SystemEvent.INIT.value, handle_init),<br>            (CustomEvent.RESET.value, handle_reset),<br>            (CustomEvent.MAP_UPDATE.value, handle_update),<br>            (CustomEvent.JUDGE.value, handle_judge),<br>        ),<br>    )<br><br>    return application</pre><p>A new helper add_event_listeners was written for adding multiple event listeners, though they work similarly as the add_event_listener we discussed last week. In case you are wondering at this point, yes, this is all we needed to implement our tic-tac-toe game. Since we split out the orchestration code to another module, our run function now becomes:</p><pre>from core import main_loop<br><br>async def run() -&gt; None:<br>    await main_loop(setup())</pre><p>Remember main_loop() takes an Awaitable as argument? This is the reason why setup() was written as a coroutine function, and passed into main_loop function without the await keyword.</p><p>Before we start the display update and event dispatching cycles, let’s initialize the game by drawing relevant elements to the application screen object:</p><pre>async def handle_init(<br>    _event: pygame.event.Event, target: Application, logger: BoundLogger, **detail: Any<br>):<br>    for row, col in product(range(3), range(3)):<br>        element = await box_draw(target, row, col, 100)<br>        element = await add_event_listener(<br>            element,<br>            pygame.MOUSEBUTTONDOWN,<br>            handle_box_click,<br>        )<br>        await target.delta_data.put(DeltaAdd(ApplicationDataField.ELEMENTS, element))<br>        await screen_update(target, element)  # type: ignore<br><br>    pygame.event.post(pygame.event.Event(CustomEvent.RESET.value))</pre><p>During the initialization phase, the handler draws the 3 x 3 tiles to the screen via box_draw, and then registers a mouse click event to each of them. Each tile is then sent to 2 queues, one to populate the application.elements tuple (via target.delta_data.put), and another to update the display (via screen_update). Once done, the handler invokes the RESET event to start a new game.</p><pre>async def handle_reset(<br>    _event: pygame.event.Event, target: Application, logger: BoundLogger, **detail: Any<br>):<br>    await state_merge(target, &quot;board&quot;, winner=None, state=GameState.RING, board=None)<br><br>    for element in target.elements.values():<br>        delta = await box_redraw(target, (255, 255, 255), element, Symbol.EMPTY)  # type: ignore<br>        await target.delta_data.put(<br>            DeltaUpdate(ApplicationDataField.ELEMENTS, element, delta)<br>        )<br>        await screen_update(target, delta)</pre><p>As the game is resetting, it first reinitializes the game state via state_merge.The helper sends a DeltaOperation to update application.state to</p><pre>{<br>    &quot;board&quot;: {<br>        &quot;winner&quot;: None,<br>        &quot;state&quot;: GameState.END,<br>        &quot;board&quot;: None<br>    }<br>}</pre><p>Elements in the game board also get redrawn (via box_redraw) to ensure they do not contain a ring or cross symbol. As we did earlier, all of them are then sent to the queues for application and display update.</p><p>Our game is now accepting input. And once a click is registered, the registered event handler is called.</p><pre>async def handle_box_click(<br>    _event: pygame.event.Event,<br>    target: Box,<br>    application: Application,<br>    logger: BoundLogger,<br>    **detail: Any,<br>) -&gt; None:<br>    element = None<br><br>    match state_get(application, &quot;board&quot;).get(&quot;state&quot;):<br>        case GameState.END:<br>            await logger.ainfo(&quot;END&quot;)<br>            pygame.event.post(pygame.event.Event(CustomEvent.RESET.value))<br><br>        case GameState.TIE:<br>            await logger.ainfo(&quot;TIE&quot;)<br>            pygame.event.post(pygame.event.Event(CustomEvent.RESET.value))<br><br>        case GameState.RING if target.value == Symbol.EMPTY:<br>            element = await box_update(<br>                application,<br>                target,<br>                Symbol.RING,<br>            )<br>            await state_merge(application, &quot;board&quot;, state=GameState.CROSS)<br><br>        case GameState.CROSS if target.value == Symbol.EMPTY:<br>            element = await box_update(<br>                application,<br>                target,<br>                Symbol.CROSS,<br>            )<br>            await state_merge(application, &quot;board&quot;, state=GameState.RING)<br><br>        case _:<br>            await logger.aerror(&quot;Invalid click&quot;)<br><br>    if element:<br>        pygame.event.post(pygame.event.Event(CustomEvent.MAP_UPDATE.value))</pre><p>Click events are handled differently, depending on the state of the board. If there is no valid moves available, in the events of an ended or tie game, then we log a message, and emit a RESET event. Otherwise, we update the clicked element to the symbol corresponding to the current state of the board, followed by a board state change for the next symbol. Lastly, we trigger a MAP_UPDATE event to update the current mapping of the board for judging.</p><pre>@dataclass<br>class BoardMap:<br>    mapping: dict[tuple[int, int], Symbol]<br><br>async def handle_update(<br>    _event: pygame.event.Event, target: Application, logger: BoundLogger, **detail: Any<br>):<br>    await state_merge(<br>        target,<br>        &quot;board&quot;,<br>        map=BoardMap(<br>            {<br>                (item.column, item.row): item.value<br>                for item in target.elements.values()<br>                if isinstance(item, Box)<br>            }<br>        ),<br>    )<br><br>    pygame.event.post(pygame.event.Event(CustomEvent.JUDGE.value))</pre><p>BoardMap is just a dataclass keeping the current state of the board, what symbol is placed at each tile. As soon as it is updated, a JUDGE event is triggered to evaluate the game.</p><pre>WIN_LINES = [<br>    # Rows<br>    {(0, 0), (0, 1), (0, 2)},<br>    {(1, 0), (1, 1), (1, 2)},<br>    {(2, 0), (2, 1), (2, 2)},<br>    # Columns<br>    {(0, 0), (1, 0), (2, 0)},<br>    {(0, 1), (1, 1), (2, 1)},<br>    {(0, 2), (1, 2), (2, 2)},<br>    # Diagonals<br>    {(0, 0), (1, 1), (2, 2)},<br>    {(0, 2), (1, 1), (2, 0)},<br>]<br><br>async def handle_judge(<br>    _event: pygame.event.Event, target: Application, logger: BoundLogger, **detail: Any<br>):<br>    if not (bmap := state_get(target, &quot;board&quot;).get(&quot;map&quot;)):<br>        return<br><br>    tiles, winner = (), None<br><br>    for symbol in (Symbol.RING, Symbol.CROSS):<br>        places = {coor for coor, item in bmap.mapping.items() if symbol == item}<br><br>        for line in WIN_LINES:<br>            if line.issubset(places):<br>                winner = symbol<br>                tiles = line<br>                break<br><br>        if winner:<br>            break<br><br>    if winner:<br>        await logger.ainfo(&quot;Winner is found&quot;, winner=winner)<br>        await state_merge(target, &quot;board&quot;, winner=winner, state=GameState.END)<br><br>        for element in target.elements.values():<br>            if (element.column, element.row) in tiles:  # type: ignore<br>                delta = await box_redraw(target, (255, 255, 0), element, winner)  # type: ignore<br>                await target.delta_data.put(<br>                    DeltaUpdate(ApplicationDataField.ELEMENTS, element, delta)<br>                )<br>                await screen_update(<br>                    target,<br>                    delta,  # type: ignore<br>                )<br>    elif (<br>        len([symbol for _, symbol in bmap.mapping.items() if symbol == Symbol.EMPTY])<br>        == 0<br>    ):<br>        await logger.ainfo(&quot;End with a tie&quot;)<br>        await state_merge(target, &quot;board&quot;, state=GameState.TIE)</pre><p>Not the most robust code I would proudly print on a t-shirt and parade with it. Essentially, it judges the game to find the winning line and symbol. Redrawing the winning tiles will take place whenever applicable. Besides that, the relevant state of the board is also queued for update (either an END or TIE) whenever needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hZL4Bm3asPWiieXpsof8Q.png" /></figure><p>By utilizing events and state_merge strategically, the simple game of tic-tac-toe is implemented. All the event dispatching work and display update are completely handled by the framework itself. All we needed to do, when changes occur, is to submit the change to the relevant queue. While there are certainly potential improvements to be made, as a weekend project I deem it good enough.</p><h3>Beyond Tic-Tac-Toe: Lessons Learned and What’s Next</h3><p>Can we build more things with it?</p><p>Short answer to the question is yes, but I don’t see much point in doing so for most people. Instead, we should reflect on what we learned so far. What is the purpose of the project? What have we achieved so far? What do we do with this piece of code?</p><p>Extracting the orchestration code into a framework is a totally unexpected outcome. Yet, I am happy with the turns of events leading to what we have now. With some polish, the resulting framework should be able to be applied for other simple graphical applications. Personally, I am quite curious on seeing how the framework scales with more elements on screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fEbkPFllr5iRzZ_h" /><figcaption>Photo by <a href="https://unsplash.com/@danfreemanphoto?utm_source=medium&amp;utm_medium=referral">Dan Freeman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As an experimental project, it certainly is quite rough on the edges. Much thought and polish are still needed in the framework API design for consistency. There are also some experimental code snippets that are not covered in the article as they are irrelevant to the game featured this week. Some of the most interesting helpers I can’t wait to try out are the functions inspired by setTimeout and element.dispatchEvent().</p><p>Perhaps a re-implementation of <a href="https://kitfucoda.medium.com/code-rains-revelation-embracing-existence-before-perfection-60f5c641963a">the code rain animation a-la the Matrix</a>?</p><p><a href="https://kitfucoda.medium.com/code-rains-revelation-embracing-existence-before-perfection-60f5c641963a">Code Rain&#39;s Revelation: Embracing Existence Before Perfection</a></p><p>Now, back to the original question asked earlier, at the beginning of this section. The framework is proven capable of building a simple game, as shown in this article. Despite that, do go for a proper game engine like Godot for serious projects. Treat the work presented here as a personal passion project, though I am open for feedback and collaboration. Seriously, this exploration makes me appreciate how game engines do all the heavy-lifting work.</p><p>Finally, thanks for reading this far. If you are interested in checking out the project, it is still hosted on GitHub at <a href="https://github.com/Jeffrey04/pygame-ttt/">the same repository</a>. Though I cannot commit to a fixed publication schedule due to my new job, I shall try writing again soon.</p><p>A quick note on how this article came together. While Gemini helped with the drafting and refining of the language, all the core ideas, the technical insights, and every line of code you’ve seen are entirely mine. This project truly reflects my personal journey and passion for Python development. If you enjoyed this deep dive and want to follow more of my explorations into coding and game development, consider subscribing or following me on <a href="https://kitfucoda.medium.com/">Medium</a>. Your support means a lot!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea7ed54ec705" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/the-pygame-framework-i-didnt-plan-building-tic-tac-toe-with-asyncio-and-events-ea7ed54ec705">The Pygame Framework I Didn’t Plan: Building Tic-Tac-Toe with Asyncio and Events</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dives: My Kitfucoda.medium.com Article Series Index (2025 Edition)]]></title>
            <link>https://kitfucoda.medium.com/deep-dives-my-kitfucoda-medium-com-article-series-index-2025-edition-63915eb10436?source=rss-6bb1e0cf9cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/63915eb10436</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[KitFu Coda]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 06:38:42 GMT</pubDate>
            <atom:updated>2025-06-25T06:56:06.673Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, fellow tech explorers!</p><p>Over time, I’ve had the immense pleasure of diving deep into various technical subjects and sharing those journeys on <a href="https://kitfucoda.medium.com/">kitfucoda.medium.com</a>. While each article stands on its own, some topics simply demand more than a single post can offer. This is where my article series come in — they’re my way of breaking down complex subjects into digestible, progressive parts, much like tackling a large coding project one function at a time. Consider this page your personal guide to these multi-part stories, designed to help you navigate through the interconnected insights and build a comprehensive understanding of the topics that truly excite us in the world of technology. I hope you find these series as enriching to read as they were for me to write!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwyzf7DJup9FZzkz2CFyYw.png" /><figcaption>Welcome to KitFu Coda. Illustration from <a href="https://copilot.microsoft.com/">Microsoft Copilot</a></figcaption></figure><h3><strong>As Seen Elsewhere: Highlighted Articles</strong></h3><p>It’s always incredibly rewarding to see the conversations sparked by my articles extend beyond Medium. This “Featured Stories” section is a curated collection of pieces that have, at various times, been highlighted in external newsletters, shared widely on social media, or even mentioned in other publications. These are the articles that resonated broadly, reaching new audiences and driving interesting discussions outside of Kitfucoda.medium.com. I’m excited for you to explore these externally recognized deep dives!</p><ul><li><a href="https://python.plainenglish.io/leveling-up-llm-game-development-with-dspy-0b203a27a15f">Leveling Up LLM Game Development with DSPy</a></li><li><a href="https://ai.plainenglish.io/vibe-coding-storytelling-and-llms-a-collaborative-approach-db5e9a62c8b1">Vibe-Coding, Storytelling, and LLMs: A Collaborative Approach</a></li></ul><h3><strong>AsyncIO Mastery: Concurrency in Python</strong></h3><p>Embarking on asynchronous programming felt like learning a new language, but the power it unlocked for handling concurrent operations was undeniable. In this series, we break down AsyncIO from the ground up, moving from fundamental awaitables to building a robust task scheduler and understanding true scalability. Get ready to supercharge your Python applications and avoid those pesky blocking waits!</p><ul><li><a href="https://kitfucoda.medium.com/understanding-awaitables-coroutines-tasks-and-futures-in-python-a9c12890d20d">Understanding Awaitables: Coroutines, Tasks, and Futures in Python</a></li><li><a href="https://kitfucoda.medium.com/asyncio-task-management-a-hands-on-scheduler-project-bd7b7fe58c7e">AsyncIO Task Management: A Hands-On Scheduler Project</a></li><li><a href="https://kitfucoda.medium.com/concurrency-vs-parallelism-achieving-scalability-with-processpoolexecutor-c366bfcc6207">Concurrency vs. Parallelism: Achieving Scalability with ProcessPoolExecutor</a></li></ul><h3><strong>Building Your Own Telegram Bots: A Deep Dive</strong></h3><p>Building a Telegram bot has been one of those projects that truly brings together a lot of different coding concepts, from asynchronous programming to managing shared state. This series takes you through my hands-on journey of crafting a Python-based Telegram bot, exploring how to handle messages, manage tasks efficiently, and keep your bot responsive. If you’ve ever wanted to create your own digital assistant or just understand the mechanics behind interactive bots, this is for you!</p><ul><li><a href="https://kitfucoda.medium.com/writing-a-telegram-bot-in-python-866972ab63f5">How to write an AsyncIO Telegram bot in Python</a></li><li><a href="https://python.plainenglish.io/telegram-chatbots-evolution-decoupling-parallel-python-s-shared-state-for-clarity-e76880ce9b1f">Telegram Chatbot’s Evolution: Decoupling Parallel Python’s Shared State for Clarity</a></li></ul><h3><strong>Crafting Games with LLMs: A Developer’s Playground</strong></h3><p>The idea of LLMs breathing life into game mechanics fascinated me, leading to a fun journey of experimentation. This series chronicles my hands-on experience building interactive word games and evolving them with advanced techniques like DSPy. Join me to explore the exciting intersection of AI and game development!</p><ul><li><a href="https://kitfucoda.medium.com/i-built-a-word-guessing-game-with-llm-84aefcf7edeb">I built a word guessing game with LLM</a></li><li><a href="https://python.plainenglish.io/leveling-up-llm-game-development-with-dspy-0b203a27a15f">Leveling Up LLM Game Development with DSPy</a></li><li><a href="https://python.plainenglish.io/the-quest-continues-porting-the-word-game-with-asyncssh-51e40b43afa5">The Quest Continues: Porting the Word Game With AsyncSSH</a></li></ul><h3><strong>My Advent of Code Journey: Problem-Solving Challenges</strong></h3><p>Every year, Advent of Code throws fascinating puzzles my way, pushing my problem-solving skills to new limits (and sometimes, my sanity!). In this series, I share my approaches and insights for tackling specific Advent of Code 2024 challenges, from parsing intricate inputs to optimizing complex algorithms. Let’s conquer these coding riddles together!</p><ul><li><a href="https://kitfucoda.medium.com/how-to-parse-computer-code-advent-of-code-2024-day-3-140c567288e4">How to parse computer code, Advent of Code 2024 day 3</a></li><li><a href="https://kitfucoda.medium.com/how-to-code-a-sorting-algorithm-for-advent-of-code-2024-cfab175ffcfd">How to code a Sorting Algorithm for Advent of Code 2024 day 5</a></li><li><a href="https://kitfucoda.medium.com/how-to-trace-steps-in-a-map-advent-of-code-2024-day-6-e9ac6ed25717">How to trace steps in a map, Advent of Code 2024 day 6</a></li><li><a href="https://kitfucoda.medium.com/how-to-repair-a-bridge-advent-of-code-2024-day-7-d954ae7b115e">How to repair a bridge, Advent of Code 2024 Day 7</a></li><li><a href="https://kitfucoda.medium.com/climbing-a-depth-first-search-hill-advent-of-code-2024-day-10-2c1490ffbf04">Climbing a depth-first search hill, Advent of Code 2024, day 10</a></li><li><a href="https://kitfucoda.medium.com/finally-an-application-for-my-fsm-library-advent-of-code-2024-day-11-714b6f0faf86">Finally, an application for my FSM library! Advent of Code 2024 day 11</a></li><li><a href="https://kitfucoda.medium.com/applying-cramers-rule-for-advent-of-code-2024-day-13-3b5ec201a307">Applying Cramer’s Rule for Advent of Code 2024, day 13</a></li></ul><h3>Beyond the Series: My Personal Projects &amp; Explorations</h3><p>Sometimes, a fascinating idea or a nagging problem leads to a standalone project that might not fit neatly into a longer series, but offers its own unique lessons and insights. This section highlights some of those personal ventures and explorations — from unexpected builds to deep dives into specific challenges — that I found particularly engaging or rewarding. Think of these as my “lab notes” from the coding trenches.</p><ul><li><a href="https://kitfucoda.medium.com/building-a-desktop-launcher-e702d7e5ba17">Building a desktop launcher</a></li><li><a href="https://kitfucoda.medium.com/remaking-a-rule-engine-dsl-82296415a2b8">Remaking a rule-engine DSL</a></li><li><a href="https://kitfucoda.medium.com/building-state-machine-library-with-help-from-ai-tools-7b82ccdca25c">Building state machine library with help from AI tools</a></li><li><a href="https://kitfucoda.medium.com/a-love-story-in-code-building-my-self-hosted-photo-album-b56a4e89ebdd">A Love Story in Code: Building My Self-Hosted Photo Album</a></li><li><a href="https://kitfucoda.medium.com/code-rains-revelation-embracing-existence-before-perfection-60f5c641963a">Code Rain&#39;s Revelation: Embracing Existence Before Perfection</a></li><li><a href="https://kitfucoda.medium.com/my-pygame-evolution-embracing-asyncio-and-immutability-for-scalable-design-84eae4601717">My Pygame Evolution: Embracing Asyncio and Immutability for Scalable Design</a></li></ul><h3>Learnings from the Field: Workshops &amp; Conferences</h3><p>Beyond the keyboard, some of my most impactful learning experiences come from engaging with the wider tech community at workshops and conferences. This section compiles insights and takeaways from events I’ve attended, covering everything from the latest industry standards to shifts in best practices and even thoughts on the broader implications of technology. Consider these my reflections and key learnings from being out in the field.</p><ul><li><a href="https://kitfucoda.medium.com/attending-open-government-workshop-5e1f0ed7cf42">Attending an Open Government Workshop</a></li><li><a href="https://kitfucoda.medium.com/hair-dryers-have-standards-why-not-software-a-call-for-rights-by-design-c648058f340f">Hair dryers have standards, why not software? A call for Rights by Design.</a></li></ul><h3>Algorithms Unpacked: The Core Logic Behind Code</h3><p>Algorithms often feel like the secret sauce behind efficient and elegant code, and delving into them has always been a fascinating challenge for me. This section gathers articles where I explore various algorithms, from fundamental sorting techniques to more complex search patterns, often drawing from real-world problems or coding challenges. Join me as we unpack the logic and beauty of these essential building blocks of computer science.</p><ul><li><a href="https://kitfucoda.medium.com/implementing-breadth-first-search-in-low-level-setting-de5658f68a3c">Implementing breadth-first search in low-level setting</a></li><li><a href="https://kitfucoda.medium.com/why-does-everyone-love-sorting-algorithms-cee129026115">Why does everyone love sorting algorithms?</a></li></ul><h3>The Dao of Functional Programming: My Category Theory Journey</h3><p>Category Theory has been a fascinating, albeit challenging, field to explore, and my attempts to grasp its profound concepts continue. This irregular series documents my latest dive into the “Dao of Functional Programming” by Dr. Bartosz Milewski, with a little help from AI. Join me as I share my study notes and insights, starting with the foundational ideas of objects and arrows in this abstract yet powerful world.</p><p><a href="https://kitfucoda.medium.com/dao-of-functional-programming-chapter-1-clean-state-4ade728a708b">Dao of Functional Programming (Chapter 1: Clean State)</a></p><p>While this introduction, and indeed all introductory texts within this guide, were prepared with the assistance of a large language model, the voices, insights, and code demonstrated in the linked articles are entirely my own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63915eb10436" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>