Dynamically patch a Python function's source code at runtime

https://news.ycombinator.com/rss Hits: 12
Summary

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> If I were to execute something(), it would return a NotImplementedError. Now, let's say that, for some reason that I shall not speculate, I decided that I wanted something() to instead do multiplication by 2. I can create new source code: new_code = """ def something(x: int) -> int: return x * 2 """ I can do the following three magical steps to swap it in. Firstly, compile the code into bytecode: compiled = compile(new_code, "<magic>", "exec") The three arguments to compile are: The code to compile (new_code), The filename in which the code is compiled (<magic>), and The mode in which compilation happens (in this case, exec mode). On the third point, the docstring of compile explains what the three modes are: The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The compiled object now is a "code object": <code object <module> at 0x149bcbad0, file "<magic>", line 1> I can then execute the compiled code to make it imported into a particular namespace. ns = {} exec(compiled, {}, ns) Here, the three arguments passed to exec are: The code we want to execute (compiled), and in this case, by "executing" it after being compiled in exec mode, we are really just simulating an import into our namespace. The globals ({}), which in this case are passed in as an empty dictionary. These are the global variables that are available to the function at runtime. ns is the "namespace...

First seen: 2025-08-24 13:10

Last seen: 2025-08-25 00:11