Python generating Python
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).
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.