Runtime Code Generation — ELI5

Imagine a chef who follows recipes from a cookbook. That is how most programs work — the code is written ahead of time, and the computer follows the instructions.

Now imagine a chef who can invent new recipes while cooking dinner. A customer says “I want something spicy with pasta” and the chef writes a brand-new recipe on the spot, then cooks it immediately. No cookbook needed.

Python can do exactly this. While your program is running, Python can create entirely new code — new functions, new classes, even new programs — and run them right away. This is called runtime code generation.

The simplest way is with exec(). You give Python a string of code, and it runs it:

code = "print('Hello from generated code!')"
exec(code)  # prints: Hello from generated code!

But the real power comes from generating code that is different each time. Your program looks at the situation — what data it has, what the user wants — and writes code tailored to that exact need.

Think about how websites work. When you visit a page, the server often generates custom HTML just for you — your name, your orders, your preferences. Runtime code generation in Python does something similar, but with executable code instead of web pages.

Libraries use this technique everywhere. When you define a class with @dataclass, Python generates __init__, __repr__, and __eq__ methods for you at runtime. It looks at your class fields and writes the perfect methods — no human needed.

It feels a bit magical, but it is just Python using its own building blocks to create new building blocks on the fly.

One thing to remember: Runtime code generation means Python can create and run new code while your program is already running — building custom functions and classes on the fly based on whatever information is available at that moment.

pythonmetaprogrammingcode-generation

See Also

  • Python Custom Import Hooks How Python's import system can be customized to load code from anywhere — databases, URLs, or even entirely new file formats.
  • Python Dsl Design Patterns How to create mini-languages inside Python that let people express complex ideas in simple, natural words.
  • Python Macro Systems How Python lets you build shortcuts that write code for you — like having magic stamps that expand into whole paragraphs.
  • Ci Cd Why big apps can ship updates every day without turning your phone into a glitchy mess — CI/CD is the behind-the-scenes quality gate and delivery truck.
  • Containerization Why does software that works on your computer break on everyone else's? Containers fix that — and they're why Netflix can deploy 100 updates a day without the site going down.