Dynamic Function Construction with types.FunctionType
Functions in Python are runtime wrappers around immutable `types.CodeType` objects. Using `types.FunctionType(code_obj, globals())`, you can synthesize new functions directly from raw compiled code objects 🧬.
import types
src = "def dynamic_calc(a, b): return a * 10 + b"
compiled = compile(src, "<runtime>", "exec")
fn_code = [c for c in compiled.co_consts if isinstance(c, types.CodeType)][0]
calc = types.FunctionType(fn_code, globals())
print(f"Result: {calc(3, 7)} 🧬")
# 70. Dynamic Function Construction with types.FunctionType Functions in Python are runtime wrappers around immutable `types.CodeType` objects. Using `types.FunctionType(code_obj, globals())`, you can synthesize new functions directly from raw compiled code objects 🧬. ```python import types src = "def dynamic_calc(a, b): return a * 10 + b" compiled = compile(src, "<runtime>", "exec") fn_code = [c for c in compiled.co_consts if isinstance(c, types.CodeType)][0] calc = types.FunctionType(fn_code, globals()) print(f"Result: {calc(3, 7)} 🧬") ``` Because `code` objects are immutable in CPython, any runtime bytecode transformations require synthesizing new code objects via `code.replace(...)` before building functions ⚡! --- ### Question Which internal attribute holds a Python function's compiled bytecode and local variable metadata? 🧠- [ ] a. `func.__code__`, referencing an immutable `types.CodeType` object 🧬 - [ ] b. `func.__dict__`, containing OS process memory offsets - [ ] c. `func.__defaults__`, which compiles default argument byte vectors - [ ] d. `func.__closure__`, which stores CPU instruction pointers --- ### Challenge Compile `'def multiply(a, b): return a * b'`. Extract its inner `CodeType` object from `co_consts`. Instantiate a function using `types.FunctionType`. Call it with `(6, 7)` and print the result. 🎯 <details> <summary>Solution</summary> ```python import types src = 'def multiply(a, b): return a * b' co = compile(src, '<dyn>', 'exec') fn_code = [c for c in co.co_consts if isinstance(c, types.CodeType)][0] multiply = types.FunctionType(fn_code, globals()) print(multiply(6, 7)) ``` </details>