Tech News
← Back to articles

Dynamically patch a Python function's source code at runtime

read original related products more articles

written by Eric J. Ma on | tags:

In this blog post, I share how I discovered a powerful Python trick: dynamically changing a function's source code at runtime using the compile and exec functions. This technique enabled me to build more flexible AI bots, like ToolBot, that can generate and execute code with access to the current environment. While this opens up exciting possibilities for LLM-powered agents and generative UIs, it also raises serious security concerns. Curious how this hack can supercharge your AI projects—and what risks you should watch out for?

So today, I learned a very dangerous and yet fascinating trick.

It's possible to dynamically change a Python function's source code at runtime.

What this does is open a world of possibilities in building AI bots!

How this actually works

Every function has a .__code__ attribute. For example, for this function:

def something (): raise NotImplementedError ()

something.__code__ looks like this:

< code object something at 0x149bdfc90 , file "/var/folders/36/vb250n_s0zncstw3sk74qfxr0000gn/T/marimo_80086/__marimo__cell_kJqw_.py" , line 1 >

... continue reading