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.

Answer from S.Lott on Stack Overflow
๐ŸŒ
Python
python.org โ€บ about โ€บ success โ€บ cog
Cog: A Code Generation Tool Written in Python
We could then use this general purpose tool to solve our specific generation problem. The tool I wrote is called Cog. Its requirements were: We needed to be able to perform interesting computation on the schema to create the code we needed. Cog would have to provide a powerful language to write the code generators in.
Discussions

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
Generate python code from a generic template
This sounds like an X-Y question, I think you should describe your larger goal rather than asking how to implement this specific solution. Generating code is usually a bad idea and usually not necessary. More on reddit.com
๐ŸŒ r/learnpython
7
0
February 7, 2023
Python code generator - Stack Overflow
The tool first parses the code ... 3 code from that tree. This may be a good place to start because this is an "official" Python tool endorsed by the core developers, and part of the recommended Python 2 to 3 migration path. Alternatively, check out the codegen.py module, which generates Python code ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
AI code generator for python
I use PyCharm's AI assistant for code generation. It's pretty efficient. More on reddit.com
๐ŸŒ r/dataengineering
5
0
August 23, 2024
๐ŸŒ
GitHub
github.com โ€บ jaap3 โ€บ sourcebuilder
GitHub - jaap3/sourcebuilder: A simple way to generate (Python) code using Python code.
January 6, 2022 - A simple way to generate (Python) code using Python code. - jaap3/sourcebuilder
Author ย  jaap3
๐ŸŒ
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
๐ŸŒ
MLQ
mlq.ai โ€บ tools โ€บ python-code-generator
Python Code Generator
Our AI-powered Python Code Generator helps you quickly create accurate Python code from plain language descriptions.
๐ŸŒ
InfoWorld
infoworld.com โ€บ home โ€บ software development โ€บ programming languages โ€บ python
PythoC: A new way to generate C code from Python | InfoWorld
December 19, 2025 - PythoC doesnโ€™t yet have a mechanism for re-using compiled code when itโ€™s called from Python, the way Cython does. At first this seems like a pretty big limitation. But itโ€™s actually the point: You can use PythoC as a code generation system for C programs that run independently, rather than C modules imported into Python.
๐ŸŒ
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
Find elsewhere
๐ŸŒ
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!
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ building a python code generator
Building a Python Code Generator | Towards Data Science
March 5, 2025 - A Decoder that decodes the state representation vector to generate the target output sequence. I have explained each of these components in detail along with a code walkthrough in my previous blog. Letโ€™s now see how we can feed data into our transformer. We will be using a custom dataset curated by The School of AI(TSAI) to train our model. This dataset contains about 5000 data points where each data point comprises an English problem statement and its corresponding Python code.
๐ŸŒ
CodeConvert AI
codeconvert.ai โ€บ python-code-generator
Free Python Code Generator โ€” AI-Powered | CodeConvert AI
This tool can generate a wide range of Python code, from simple functions, algorithms, and data structures to complete programs with classes, error handling, and file I/O.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ generate python code from a generic template
r/learnpython on Reddit: Generate python code from a generic template
February 7, 2023 -

Hi,

I need to write a console wizard that will ask several questions, and based on the answers and/or input, it will generate a py file.

For example:

$ python3 wizard.py

  • Name? IntelBP

  • Country? USA

Writing file ... Include.py generated.

$ cat include.py

name='IntelBP' country='USA'

... EOF.

So basically, what i need is a wizard engine that asks questions, and based on the answers, it reads a template (python code) and fills in some variables.

So there's essentially 2 aspects to this question:

  1. What package can I use for writing the console interface? Ideally it will support text, lists, single, and multiple values for a specific wizard question.

  2. Are there any packages designed to populate the values from the template into a python file? My greater concern is security related issues such as code injection.

Thanks!!

๐ŸŒ
CodePal
codepal.ai โ€บ code-generator โ€บ python
Python Code Generator - CodePal
CodePal is an AI coding companion with tools to generate, fix, refactor and explain code in 60+ languages.
๐ŸŒ
Refact.ai
refact.ai โ€บ python-code-generator
AI Python Code Generator - Free Tool by Refact.ai - Refact.ai
Try the best free Python code web generator. Write scripts from JSON to file and generate strings without login required.
๐ŸŒ
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.
Top answer
1 of 2
19

You may want to take a look at the 2to3 tool, developed by the Python code devs to automatically convert Python 2 code to Python 3 code. The tool first parses the code to a tree, and then spits out "fixed" Python 3 code from that tree.

This may be a good place to start because this is an "official" Python tool endorsed by the core developers, and part of the recommended Python 2 to 3 migration path.

Alternatively, check out the codegen.py module, which generates Python code back from Python's ast.

See also this SO question, which may be relevant to yours (I'm not marking it a duplicate because I'm not sure the scopes of the questions overlap 100%)

2 of 2
5

Automatic code generation is commonly done in the following ways:

  • Print statements containing code fragments
  • Text templates with placeholders (think macros)

IMHO, better practice is:

  • Built an AST for the target fragment, and then prettyprint

Hardly anybody does the latter, because the tools are mostly not there.

Python's 2to3 tool provides (I think) the target AST and prettyprinting.

But a question you didn't ask, is "generate from what?" Somehow you have to specify abstractly what you want generated (or it isn't a win). And your tool has to be able to read that specification somehow.

Many code generation schemes consist of writing procedural code that calls the above generation mechanisms; the procedural code acts as an implicit specification. It is "easy" to read the specification; it is just code in the language used by the code generator.

Some code generation schemes use some kind of graph structure to provide a frame on which fragments of specification are hung, that drive the code generation. UML class diagrams are a classic example. These schemes aren't so easy; you need a "specification reader" (e.g., UML diagram reader aka XMI or some such, or if you aren't using UML, some kind of specification parser), and then you need something to climb over the just-read specification in some useful order (UML is graph, there are many different ways it can be visited), that makes calls on code generation steps.

The Python 2to3 tool uses a Python2 parser to read the "spec". If you want to generate code from Python2, that will be fine. I suspect you don't want to do that.

A best practice approach is one that unifies the ability to read/analyze/traverse specifications, with the ability to produce ASTs for the target language.

Our DMS Software Reengineering Toolkit is a general purpose program analysis and transformation system. It parses "specifications" (instances of grammars to you can define to it) into ASTs; it will also let you build arbitrary ASTs for any of those grammars, using either procedural code [as sketched above] or using pattern-match/replacement (pretty much unique to DMS). Part of a DMS langauge front end is a prettyprinter, that can regenerate text from ASTs (these are tested by roundtripping code: parse to AST, prettyprint AST, better be the same text).

In case your grammar isn't known to DMS, it has extremely good parser and prettyprinter generators, as well as other support mechanisms for analyzing programs. All that additional machinery is usually not available with classic parser generators, or with just a plain "AST" package. (I don't know what is in 2to3).

The relevance of this to Python is that DMS has a Python front end as well as grammars for many other languages.

So, you can use DMS to parse your specification, and to generate Python code using ASTs, finally followed by prettyprinting.

๐ŸŒ
MyMap AI
mymap.ai โ€บ home โ€บ tools
Free Python Code Generator: Create Code in Seconds
Describe your idea. MyMap's AI will generate a custom map from scratch.Start from scratch
๐ŸŒ
JIT.dev
jit.dev โ€บ python-code-generator
Python Code Generator - JIT - AI Code Playground
Effortlessly generate Python code with our AI-powered Python Code Generator. Boost your productivity and coding speed.