Back
+20 XP
Concept

Dynamic Bytecode Synthesis: types.CodeType & FunctionType

Functions are runtime wrappers around immutable `types.CodeType` instances. Using `compile()` and `types.FunctionType`, you can construct executable Python functions directly from synthesized AST code objects, injecting custom global namespaces and closures on the fly 🧠⚡.

python
import types

# Compile source string into executable CodeType:
module_code = compile("def multiply(a, b): return a * b", "<synthetic>", "exec")

# Extract the inner function code object from co_consts:
func_code = next(c for c in module_code.co_consts if isinstance(c, types.CodeType))

# Bind code object to global environment as a first-class function:
synthesized_func = types.FunctionType(func_code, globals(), "multiply")

print(f"Synthesized Function Output: {synthesized_func(6, 7)} 🚀")

# 84. Dynamic Bytecode Synthesis: types.CodeType & FunctionType In high-performance RPC systems, template engines (Jinja), or dynamic query builders, using `eval()` or `exec()` on every incoming request is slow and insecure. The professional approach is compiling dynamic code into a `CodeType` once and executing it at native bytecode speed 🛑. ```python # The Anatomy of a Python Function: # def foo(): pass # type(foo) -> types.FunctionType (Mutable wrapper: __name__, __doc__, __dict__) # foo.__code__ -> types.CodeType (Immutable compiled C struct) # foo.__code__.co_code -> Raw bytes of CPython VM opcodes! # foo.__code__.co_consts -> Tuple of literals used by the function # foo.__code__.co_varnames-> Tuple of local variable names ``` ### Dynamic Synthesis Pipeline 1. **Compilation**: `compile(source, filename, mode)` parses the Python grammar, generates the AST, and compiles it down to a CPython `PyCodeObject` without executing it. 2. **`co_consts` Inspection**: Inner functions and lambdas are stored as constant literals inside the enclosing module's `co_consts` tuple. 3. **`types.FunctionType(code, globals, name)`**: Instantiates a genuine callable Python function wrapping the code object, binding it to whichever custom dictionary namespace you specify 🧠⚡. --- ### Interactive Pop-Quiz 🧠 #### Where does a compiled module's CodeType object store the nested CodeType objects of functions defined inside it? - [ ] Inside the co_consts tuple of constants 🧠 - [ ] In the operating system swap space - [ ] Inside the co_names variable identifier array - [ ] In a dedicated SQLite temporary database --- ### Practical Challenge 🎯 Compile `'def square(n): return n * n'` into a code object. Extract the inner function `CodeType` from `co_consts`. Instantiate a `types.FunctionType` named `'square'`. Execute it with argument `8`. Verify the result equals `64`, and print the synthesized function's return value. <details> <summary>Solution</summary> ```python import types module_code = compile("def square(n): return n * n", "<dyn>", "exec") func_code = next(c for c in module_code.co_consts if isinstance(c, types.CodeType)) square_fn = types.FunctionType(func_code, globals(), "square") result = square_fn(8) assert result == 64 print(result) ``` </details>

Checkpoint

Where does a compiled module's `CodeType` object store the nested `CodeType` objects of functions defined inside it? 🧠

Practice

Compile `'def square(n): return n * n'` into a code object. Extract the inner function `CodeType` from `co_consts`. Instantiate a `types.FunctionType` named `'square'`. Execute it with argument `8`. Verify the result equals `64`, and print the synthesized function's return value. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks