The Wicked Trick: Dynamically Patching Python Function Source Code at Runtime

2025-08-24

This post details a fascinating yet dangerous technique: dynamically altering a Python function's source code at runtime. By manipulating the `.__code__` attribute, recompiling, and injecting into a namespace, the author demonstrates dynamic function replacement. This powers LlamaBot's ToolBot, which focuses on tool selection, not execution. Generated code compiles and runs in the same Python environment, accessing runtime variables for enhanced AI capabilities. While security risks exist, this showcases Python's flexibility and the importance of separating tool selection from execution in LLM agents.

Read more
Development Dynamic Code