Python: I Mustache You a Question
August 6, 2022
August 6, 2022
Do you separate your data from its presentation?
I don't officially have a Computer Science background (I got where I am via ECE), so certain concepts or terms aren't always in the forefront of my mind. One of those things is "Separation of Concerns" which is something that I like. Because many times in my career, I've inherited code that "grew organically" which is a polite way of saying that it ended up needing some marinara. It is often "fetch, process, and present the data" - all interleaved in one function / method.
msg += "Header"
# Process some data and create info_list
for info in info_list:
msg += info.field1 ...
Everything here is being shoved into a single string, which is bad form (I believe it's since Python strings are immutable, so it's really creating more strings to just garbage collect later, but I'm no expert so I may be wrong here in the details).
If this was it, honestly it would probably be acceptable, or at least a lower priority than other refactoring. But there's a lot of digging to do when the customer says "also include this in the email too." Or when you're trying to tweak the formatting and can't find where it actually happens. Or you want to drop a copy into a log file.
Enter The Template
Templates have been around for a long long time. I remember using Genshi with Trac over a decade ago! And in Python, there's a plethora available: Jinja2, Django's native backend, etc. For the simplest, there's even a built-in string.Template. But what about that forced pun in the title? There's a nice little templating language with implementations in over forty languages called Mustache.
How Easy Is It?
Here's some of the new code:
template = """