Python generating Python Python generating Python python python

Python generating Python


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.


This is pretty much the best way to generate Python source code. However, you can also generate Python executable code at runtime using the ast library. You can build code using the abstract syntax tree, then pass it to compile() to compile it into executable code. Then you can use eval() to run the code.

I'm not sure whether there is a convenient way to save the compiled code for use later though (ie. in a .pyc file).


Just read your comment to wintermute - ie:

What I have is a bunch of planets that I want to store each as their own text files. I'm not particularly attached to storing them as python source code, but I am attached to making them human-readable.

If that's the case, then it seems like you shouldn't need subclasses but should be able to use the same class and distinguish the planets via data alone. And in that case, why not just write the data to files and, when you need the planet objects in your program, read in the data to initialize the objects?

If you needed to do stuff like overriding methods, I could see writing out code - but shouldn't you just be able to have the same methods for all planets, just using different variables?

The advantage of just writing out the data (it can include label type info for readability that you'd skip when you read it in) is that non-Python programmers won't get distracted when reading them, you could use the same files with some other language if necessary, etc.