Get the latest tech news

Dynamically patch a Python function's source code at runtime


written by Eric J. Ma on 2025-08-23 | 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.

Further more, inspired by the Marimo blog post, ToolBot is designed to just do the tool picking, delegating the execution and return of the broader LLM-powered Python program back to the developer. First, Python's runtime is far more malleable than I initially realized - the ability to compile strings into executable code and inject them into specific namespaces opens up incredible possibilities for dynamic programming. This technique enabled me to build more flexible AI bots, like ToolBot, that can generate and execute code with access to the current environment.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of source code

source code

Photo of runtime

runtime

Photo of Python function

Python function

Related news:

News photo

AMD's already taken down mistakenly released FSR 4 source code, but the internet never forgets — forked Github repositories remain accessible

News photo

Convo-Lang: LLM Programming Language and Runtime

News photo

Profiling without Source code – how I diagnosed Trackmania stuttering