If I were doing this, and the code generator was itself in Python, I'd probably use ast and/or tokenize to avoid having to manipulate literal whitespace.