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
# extended by Nadin Kokciyan
import sys, string

class PyGen:

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

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

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

    def newline(self, no=1):
        i = 1        
            res += "\n"
            i += 1

    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.write("print 'code generation is trivial'")
c.write("print i")

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: