Sunday, August 28, 2011

Python on the Fly Code Generator

Hey everyone,

I know that I'm not blogging for a while. It doesn't mean that I don't have anything to share :P
I'm currently working on my master thesis and I'm using Python for coding part. Today, I was looking for a python library to be able to generate python code on the fly. Of course, first idea is to create a file, adding imports, classes, methods and so on.. I only found a helper class written by Fredrik Lundh in this blog post.

I liked this idea and extended the code just a little bit. I want to work on a more complete library in few months. Do not forget to check my blog for the updates. And here is the simple class code:

#
# a Python code generator backend
#
# fredrik lundh, march 1998
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
# extended by Nadin Kokciyan
# nadin.kokciyan@boun.edu.tr
#
import sys, string

class PyGen:

    def __init__(self):
        self.code = []
        self.tab = "    "
        self.level = 0

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

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

    def newline(self, no=1):
        res=""        
        i = 1        
        while(i<=no):
            res += "\n"
            i += 1
        self.code.append(res)

    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
Example Usage:
c = PyGen()

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

c.newline(no=5) # adding 5 new lines
c.write("print 'end of my code'") 
print c.end()
And the output is:
for i in range(1000):
    print 'code generation is trivial'
    print i




print 'end of my code'

Of course, you will create an empty py file and write this generated content to it.. Hope it helps!..

No comments: