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 Overflow
🌐
Python
python.org › about › success › cog
Cog: A Code Generation Tool Written in Python
For each chunk of generator code it finds, Cog will: ... In a word, great. We now have a powerful tool that lets us maintain a single XML file that describes our data schema. Developers changing the schema have a simple tool to run that generates code from the schema, producing output code in four different languages across 50 files.
🌐
Reddit
reddit.com › r/python › python code generation tools
r/Python on Reddit: Python Code Generation Tools
March 9, 2019 -

What 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.

Top answer
1 of 3
2
I'd probably use metaclasses if I had the kind of problem where code generation could actually help. The last time I saw a project using code generation where I thought that it ought have to used metaclasses was a tool to generate python code from swagger descriptions. Django's ORM is a good example where metaclasses were used to good effect (there are very few of those). In general I'm extremely suspicious of anybody who claims to have the kind of problem that requires either metaclasses or code generation would help though. It is suitable only for problems that are very, very, very abstract (e.g. like an ORM or REST API interaction framework). In 90% of cases I've seen the person attempting to use it vastly overgeneralized the problem that they actually had in an attempt to prepare for future problems never arose. In the process of doing that they then created a code clusterfuck that was hellishly hard to understand and debug (and in some cases I was left to clean up the mess). It wasn't simple and it can't, intrinsically, ever be simple (there is some language theory behind this). I could be convinced otherwise by describing your problem, but right now I'm 80% convinced that what you have described is an XY problem and that you're attempting to do this because you overgeneralized your problem. If you describe the actual problem you're solving it might help.
2 of 3
2
If you're looking for some codegen support stuffs in python, I'd give you some info Python std module ast AST to python source code emitter, unparse. https://github.com/python/cpython/blob/master/Tools/parser/unparse.py AST based scoping analyzer, https://github.com/thautwarm/scoping-resolver
Discussions

templates - Best Python templating library to facilitate code generation - Stack Overflow
Instead of me spending the next day (or year) reading about them all, are there any suggestions for templating engines that I should look into in more detail? More on stackoverflow.com
🌐 stackoverflow.com
code generation - Python generating Python - Stack Overflow
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. More on stackoverflow.com
🌐 stackoverflow.com
code generation - Are there any libraries for generating Python source? - Stack Overflow
I'd like to write a code generation ... generated classes. I can create the class and use it in code, but it would be nice to have a sourcefile both for documentation and to allow something to import. Does such a thing exist? I've seen sourcecodegen, but I'd rather avoid messing with the ast trees as they're not portable. ... I'm not aware of any off-the-shelf library, but have a look at the Python templating ... More on stackoverflow.com
🌐 stackoverflow.com
Python Code Generation Tools
I'd probably use metaclasses if I had the kind of problem where code generation could actually help. The last time I saw a project using code generation where I thought that it ought have to used metaclasses was a tool to generate python code from swagger descriptions. Django's ORM is a good example where metaclasses were used to good effect (there are very few of those). In general I'm extremely suspicious of anybody who claims to have the kind of problem that requires either metaclasses or code generation would help though. It is suitable only for problems that are very, very, very abstract (e.g. like an ORM or REST API interaction framework). In 90% of cases I've seen the person attempting to use it vastly overgeneralized the problem that they actually had in an attempt to prepare for future problems never arose. In the process of doing that they then created a code clusterfuck that was hellishly hard to understand and debug (and in some cases I was left to clean up the mess). It wasn't simple and it can't, intrinsically, ever be simple (there is some language theory behind this). I could be convinced otherwise by describing your problem, but right now I'm 80% convinced that what you have described is an XY problem and that you're attempting to do this because you overgeneralized your problem. If you describe the actual problem you're solving it might help. More on reddit.com
🌐 r/Python
18
8
March 9, 2019
🌐
GitHub
github.com › modm-io › lbuild
GitHub - modm-io/lbuild: lbuild: a generic, modular code generator in Python 3 · GitHub
lbuild: a generic, modular code generator in Python 3 - modm-io/lbuild
Starred by 43 users
Forked by 11 users
Languages   Python
🌐
PyPI
pypi.org › project › codegenlib
codegenlib · PyPI
import os import sys from codegenlib.parser import Parser # Own modules from codegenlib.templateStreaming import TemplateStreaming pathname = os.path.dirname(sys.argv[0]) # current path json_file_name = "sample_config_with_template_folder.json" json_file_path = pathname + "/" + json_file_name sampleJsonModule = Parser.jsonToTemplateModule(json_file=json_file_path) sampleJsonModule.outputDirectory = "oneframe-api-ios" sampleJsonModule.isAppendOutputPath = True print(sampleJsonModule.getOutputDirectoryPath()) tStreaming = TemplateStreaming( template_module=sampleJsonModule, enable_log=False, ) tStreaming.execute()
      » pip install codegenlib
    
Published   Jun 16, 2022
Version   0.8.0
🌐
SymPy
sympy.org › scipy-2017-codegen-tutorial
Automatic Code Generation with SymPy
SymPy supports generating code ... can easily be extended to other languages. SymPy’s code generation is used by libraries such as PyDy, pyodesys, sympybotics, pycalphad, and many other programs....
🌐
EA-Bridge
itemis.com › en › products › itemis-create › documentation › user-guide › codegen_python_code_generator
Python code generator
The off_button event turns the light off. When the light is on, it automatically turns off after 30 seconds. Whenever a state is entered, an outgoing event is raised. The ‘Python Code Generation’ example can be found in the example wizard: File -> New -> Example...
Find elsewhere
🌐
Medium
medium.com › @yonatanzunger › advanced-python-achieving-high-performance-with-code-generation-796b177ec79
Advanced Python: Achieving High Performance with Code Generation | by Yonatan Zunger | Medium
August 11, 2022 - In the first part, we synthesize the bytecode and line number tables, by the most direct fashion possible — writing to a BytesIO object, and getting the requisite binary opcode values out of the dis library. In the second part, we do the interfacing to turn byte code into something Python can invoke, by constructing a CodeType object (Python’s internal representation of a code object) and a FunctionType object out of that.
🌐
Qodo
qodo.ai › blog › news & updates › top 7 python code generator tools in 2025
Top 7 Python Code Generator Tools in 2025 - Qodo
May 16, 2025 - IntelliCode provides thousands of real-world examples of how to use various APIs directly within VS Code. By clicking on a suggestion, developers can browse through the examples sourced from public repositories, helping them understand how to implement specific functions or libraries effectively. While IntelliCode is particularly useful for the Python language, it also supports other languages like Java, Javascript, and Typescript.
🌐
Zeroc
archive.zeroc.com › ice › 3.6 › language-mappings › python-mapping › client-side-slice-to-python-mapping › code-generation-in-python
Code Generation in Python - Ice
It is created by slice2py and must not be edited manually. Inside the file is Python code to import the generated files that contain definitions in the Slice module of interest. For example, the Slice files Process.ice and Syscall.ice both define types in the Slice module OS.
🌐
CodingFleet
codingfleet.com › code-generator › python
Python Code Generator - CodingFleet
Meet Python Code Generator - an innovative AI-powered tool that transforms your instructions into efficient Python code. Just say what you need, and it'll generate the code. It's like having your very own Python wizard!
🌐
Kaggle
kaggle.com › code › muhammadumairab › python-code-generation
Python Code Generation
Checking your browser before accessing www.kaggle.com · Click here if you are not automatically redirected after 5 seconds
🌐
Mark's Software Blog
markvtechblog.wordpress.com › 2024 › 04 › 28 › code-generation-in-python-with-jinja2
C++ Code Generation using Python and Jinja2 | Mark's Software Blog
January 31, 2026 - This post shows a minimal, working code generator: a YAML “message spec” plus Jinja2 templates that generate C++ .h/.cpp files, with a small Python script you can copy and adapt. Throughout my care…
🌐
PyPI
pypi.org › project › code-generation
code-generation · PyPI
It could also be used for composing more complicated C++ code, that does not supported by cpp_generator · Class ANSICodeStyle is responsible for code formatting. Re-implement it if you wish to apply any other formatting style. ... The following command will execute the unit tests. ... After changing a unit test the fixed data needs to be updated to successfully pass the unit tests. python -c 'from test_cpp_generator import generate_reference_code; generate_reference_code()'
      » pip install code-generation
    
Published   Jan 31, 2023
Version   2.3.0
🌐
Etlcpp
etlcpp.com › generators_tutorial.html
generators_tutorial
This allows Python code to be embedded within the · C++. When COG is run on the generator header, it will produce a customised version of that header. ... The script generate.bat will run all of the generate scripts. ... The line above will create type_traits.h with the ability to handle up to 16 types in the etl::is_one_of structure. All of the generator files may be processed by running the script generate.bat · There are generator scripts for each generator header.
🌐
PyPI
pypi.org › project › pymultigen
Client Challenge
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
GitHub
github.com › cogu › cfile
GitHub - cogu/cfile: A python C code generator · GitHub
import cfile C = cfile.CFactory() code = C.sequence() struct = C.struct("mystruct", members=[C.struct_member("field_1", "int"), C.struct_member("field_2", "int")]) struct_type = C.typedef("my_struct_t", C.declaration(struct)) code.append(C.statement(C.declaration(struct_type))) code.append(C.blank()) code.append(C.statement(C.declaration(C.variable("instance", struct_type), [0, 0]))) writer = cfile.Writer(cfile.StyleOptions(break_before_braces=cfile.BreakBeforeBraces.ATTACH)) print(writer.write_str(code)) ... Python 3.10+ (Needed for modern type hinting support).
Starred by 92 users
Forked by 25 users
Languages   Python 99.7% | Batchfile 0.3%