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.
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.
code generation - Are there any libraries for generating Python source? - 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 generation
Preface your code generation with exact specifications:
### Python 3.7+, xxxx.py version 2.3
The fault in code generation is simply the feeble-minded-ness of ChatGPT as of late. It will screw up code again you had just made it fix. You must pretty much limit yourself to just making small functions it can understand.
If you want power programming, you can use the non-chat API, as I show doing a different task:
https://www.reddit.com/r/ChatGPT/comments/1317t3x/use_openai_gpt_models_and_api_to_be_your/
More on reddit.comVideos
» pip install codegenlib
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).
» pip install code-generation