Codefind

0.1.7 · active · verified Mon Apr 13

Codefind is a Python library (current version 0.1.7) designed for advanced code introspection, allowing users to find and manipulate code objects and their referents. It can locate code objects by filename and qualified name, identify all functions sharing a specific code object, and even modify the code of functions. This utility is notably used by the `jurigged` project for dynamic code updates. It maintains an active development status with regular, though not strictly scheduled, patch releases.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `find_code` to locate code objects, `get_functions` to retrieve all functions associated with a given code object (useful for closures), and `conform` to dynamically replace a function's underlying code with another's. The `__file__` and `__module__` arguments are crucial for `find_code` to correctly locate code within the current execution context.

from codefind import find_code, get_functions, conform

def f(x): return x + x
def adder(x):
    def f(y): return x + y
    return f

add1 = adder(1)
add2 = adder(2)
add3 = adder(3)

# Find a code object
found_f_code = find_code("f", filename=__file__)
print(f"Code object for f: {found_f_code == f.__code__}")

# Find closure code
found_adder_f_code = find_code("adder", "f", filename=__file__)
print(f"Code object for adder's inner f: {found_adder_f_code == add1.__code__}")

# Get all functions using a code object
functions_with_add1_code = set(get_functions(add1.__code__))
print(f"Functions sharing add1's code: {functions_with_add1_code == {add1, add2, add3}}")

# Dynamically conform function code
def g(x): return x * x

print(f"f(5) before conform: {f(5)}")
conform(f, g)
print(f"f(5) after conform to g: {f(5)}")

view raw JSON →