Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python generating Python

Tags:

I have a group of objects which I am creating a class for that I want to store each object as its own text file. I would really like to store it as a Python class definition which subclasses the main class I am creating. So, I did some poking around and found a Python Code Generator on effbot.org. I did some experimenting with it and here's what I came up with:

# # a Python code generator backend # # fredrik lundh, march 1998 # # [email protected] # http://www.pythonware.com # # Code taken from http://effbot.org/zone/python-code-generator.htm  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  class Point():     """Defines a Point. Has x and y."""     def __init__(self, x, y):         self.x = x         self.y = y      def dump_self(self, filename):         self.c = CodeGeneratorBackend()         self.c.begin(tab="    ")         self.c.write("class {0}{1}Point()\n".format(self.x,self.y))         self.c.indent()         self.c.write('"""Defines a Point. Has x and y"""\n')         self.c.write('def __init__(self, x={0}, y={1}):\n'.format(self.x, self.y))         self.c.indent()         self.c.write('self.x = {0}\n'.format(self.x))         self.c.write('self.y = {0}\n'.format(self.y))         self.c.dedent()         self.c.dedent()         f = open(filename,'w')         f.write(self.c.end())         f.close()  if __name__ == "__main__":     p = Point(3,4)     p.dump_self('demo.py') 

That feels really ugly, is there a cleaner/better/more pythonic way to do this? Please note, this is not the class I actually intend to do this with, this is a small class I can easily mock up in not too many lines. Also, the subclasses don't need to have the generating function in them, if I need that again, I can just call the code generator from the superclass.

like image 694
Jonathanb Avatar asked Sep 01 '09 21:09

Jonathanb


People also ask

What is Python code generator?

The Python code generator translates the state machine model into a Python class. The state machine class contains fundamental methods to enter and exit the state machine, as well as a method to execute a run-to-completion step.

How do you create a generator in Python?

Python provides a generator to create your own iterator function. A generator is a special type of function which does not return a single value, instead, it returns an iterator object with a sequence of values. In a generator function, a yield statement is used rather than a return statement.

How do Python generators work?

A Python generator is a function that produces a sequence of results. It works by maintaining its local state, so that the function can resume again exactly where it left off when called subsequent times. Thus, you can think of a generator as something like a powerful iterator.


1 Answers

We use Jinja2 to fill in a template. It's much simpler.

The template looks a lot like Python code with a few {{something}} replacements in it.

like image 186
S.Lott Avatar answered Dec 19 '22 05:12

S.Lott