A Python Code Generator

A Python Code Generator

A common complaint about Python’s syntax is that it’s impossible to generate Python code on the fly, from a program. Here’s a simple helper class that helps you do exactly that:

#
# a Python code generator backend
#
# fredrik lundh, march 1998
#
# fredrik@pythonware.com
# http://www.pythonware.com
#

import sys, string

class CodeGeneratorBackend:

    def begin(self, tab="\t"):
        self.code = []
        self.tab = tab
        self.level = 0

    def end(self):
        return string.join(self.code, "")

    def write(self, string):
        self.code.append(self.tab * self.level + string)

    def indent(self):
        self.level = self.level + 1

    def dedent(self):
        if self.level == 0:
            raise SyntaxError, "internal error in code generator"
        self.level = self.level - 1

And here’s how it can be used:

c = CodeGeneratorBackend()

c.begin(tab="    ")

c.write("for i in range(1000):\n")
c.indent()
c.write("print 'code generation is trivial'")
c.dedent()

print c.end()

Which prints:

for i in range(1000):
    print 'code generation is trivial'