Best suggestion: try them all. It won't take long.
My favourite: Jinja2 (by a mile)
It has decent syntax, can trace errors through it, and is sandboxable.
Answer from Ali Afshar on Stack OverflowWhat do you guys use to generate Python code? I saw that a lot of people just use Jinja2 with some templates, which looks simple and powerful. You still have to generate the environments and write the templates. Now I'm looking around whether someone already did the work of generalizing that step (thinking about fields in classes, inheritance, constructors etc. and how to map that data to the environment) or whether I have to do it myself.
TLDR: Are there simple but powerful Python code generation "frameworks"?
EDIT:
-
I found pymultigen. Seems like it helps with creating code in multiple files.
-
Looks like pyecoregen is a specialized multi-file code generator based on pymultigen.
templates - Best Python templating library to facilitate code generation - Stack Overflow
code generation - Python generating Python - Stack Overflow
Will devs be replaced by AI? I found this ai python code generator and it's terrifyingly good
Code generator using python
I haven't tried this myself, but the cog module sure seems interesting for a job such as this. It is in my todo list to play with it. Let me know how it goes: https://www.python.org/about/success/cog/
More on reddit.comWhat are the popular use cases supported by AI Python code generator?
Can I use Python code generator for refactoring or code optimization?
Do I need to add context to generate python code using Workik AI?
Videos
Best suggestion: try them all. It won't take long.
My favourite: Jinja2 (by a mile)
It has decent syntax, can trace errors through it, and is sandboxable.
If you're doing code generation, you might find Cog useful - it's specifically for code generation, rather than being a generally applicable templating language.
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).