Skip to main content

Saving state for rendering to the terminal with coroutines and curtsies

For the project I’m working on I’m using curtsies. Which although I like the coding style more than Urwid or npyscreen, curtsies requires a lot more low level creation of screen primitives.

The app I’m working on—Llat—has a terminal user interface (TUI) that’s interactive both by keyboard input and voice commands. While pondering implementation details of Llat, I realized that rendering to the terminal could be viewed as an infinite sequence of generated strings rendered upon receiving some sort of input. Something like: \(c’= f(c)\) Where \(c\) is the current context (or state), and \(f(c)\) is a function that creates a new state \(c’\) based off the input. What came out of this thought process was using a coroutine style generator to save state much like a closure or a class. This way the program can iterate through the generator, producing outputs based on the input. This could—and perhaps should—be done with a class, but I like the generator approach, and I think it will yield advantages latter.

Here’s a gist extracted from my experimenting showing how this was implemented.

During this process, I’ve found iteratively building upon previous techniques (as seen in the ‘my experimenting’ linked file above) to be incredibly useful for learning and developing code with libraries that are totally new to me. Taking notes on what I’ve done has helped both solidify the knowledge, ensure I actually get what’s going on, and serves as a reminder for gotchas/wats.