I really like this approach because as you said, it gets really messy to do string replacements inline in a python file.
I'm curious if any people here are comfortable using stored procedures as an alternative to this.
Stored procs give you the benefit of your sql being easy to change in a sql editor, but you also get query planner caching of the results which means it will likely execute faster than string replacement inline sql.