Code generation with Cog

Tuesday 10 February 2004This is more than 19 years old. Be careful.

Cog is a code generation tool I wrote to solve some problems at work. It’s based on embedding Python in source files to generate code (we use it to generate C++, for example).

I’m really happy with the way Cog turned out. Some would say that Cog isn’t a code generation tool at all, but just a file munger that can be used for code generation. They would be right, Cog does much less than most “code generators”. But it was written to munge files in just the way you need to when generating code. Cog only does one thing, and it does it well: it executes chunks of Python it finds in text files, capturing the output and writing it into the file alongside the original code.

Download it, try it out, and let me know what you think.

For more about code generation in general, try:

  • Dave Thomas interviewed about code generation. Dave Thomas is one of the Pragmatic Programmers, and I find I agree with him almost universally. He forbids putting the output of code generators under source control, I encourage it. We agree that the output should never be edited.
  • The Code Generation page on the c2 wiki. As will happen with a wiki, this fractures off in many directions, with many different viewpoints, both for and against code generation.


You should check out the cgn-talk Yahoo Group. There we talk about code generators and what is going on in the CG world. You may be able to get some folks interested in using your generator.
This seems pretty much like what I use empy for:
Dave Thomas is right about not having generated code checked into source control. The mechanism to create the code and the data and meta-data from which the code is created does, however, need to be under source control. Otherwise, it is too tempting for somebody to edit the source.

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.