Every code element in Codegen is an Editable - meaning it can be manipulated while maintaining correctness.All higher-level code manipulation APIs are built on top of the atomic Editable API.
There are several fundamental ways to modify code with Editables:
Copy
Ask AI
# 1. edit() - Replace entire source with new contentfunction = codebase.get_function("process_data")function.edit("""def process_data(input_data: dict) -> dict: return transform(input_data)""")# 2. Replace - Substitute text while preserving contextclass_def = codebase.get_class("UserModel")class_def.replace("user_id", "account_id") # Updates all occurrences# 3. Remove - Safely delete code with proper cleanupunused_import = file.get_import("from utils import deprecated_func")unused_import.remove() # Handles formatting, commas, etc# 4. Insert - Add code before or after an elementfunction.insert_before("# Process user input") # Adds comment before functionfunction.insert_after("""def validate_data(data: dict) -> bool: return all(required in data for required in REQUIRED_FIELDS)""") # Adds new function after
# Remove a function and its decoratorsfunction.remove() # Removes associated comments and formatting# Remove imports cleanlyimport_stmt.remove() # Handles commas and whitespace
# Get containing elementsfunction = codebase.get_function("process_data")print(function.parent_class) # Class containing this functionprint(function.parent_function) # Function containing this function (for nested functions)print(function.parent_statement) # Statement containing this function# Check if top-levelis_top_level = function.parent_class is None and function.parent_function is None
The is_wrapped_in method lets you check if an Editable is contained within specific types of statements:
Copy
Ask AI
# Check containment in statement typesis_in_try = function.is_wrapped_in("try")is_in_if = function.is_wrapped_in("if")is_in_while = function.is_wrapped_in("while")# Get the first parent statements of a certain typeif_block = function.parent_of_type(IfStatement)# Common patternsif function.is_wrapped_in(IfStatement): print("This is in an IfBlock")if variable.is_wrapped_in(WithStatement): print("Variable used in WithStatement")
# Move nested functions to module levelfor func in file.functions: if func.parent_function: # This is a nested function func.parent_function.insert_before(func.source) # Move to module level func.remove() # Remove the nested function# Find variables defined in unsafe blocksfor var in function.code_block.get_local_var_assignments(): if var.is_wrapped_in(TryStatement): print(f"Warning: {var.name} defined in try block")