Every code block (function body, loop body, etc.) provides access to its local variables:
Copy
Ask AI
# Get all local variables in a functionfunction = codebase.get_function("process_data")local_vars = function.code_block.local_var_assignmentsfor var in local_vars: print(var.name)# Find a specific variableconfig_var = function.code_block.get_local_var_assignment("config")config_var.rename("settings") # Updates all references safely# Rename a variable used in this scope (but not necessarily declared here)function.rename_local_variable("foo", "bar")
Codegen supports fuzzy matching when searching for local variables. This allows you to find variables whose names contain a substring, rather than requiring exact matches:
Copy
Ask AI
# Get all local variables containing "config"function = codebase.get_function("process_data")# Exact match - only finds variables named exactly "config"exact_matches = function.code_block.get_local_var_assignments("config")# Returns: config = {...}# Fuzzy match - finds any variable containing "config"fuzzy_matches = function.code_block.get_local_var_assignments("config", fuzzy_match=True)# Returns: config = {...}, app_config = {...}, config_settings = {...}# Fuzzy matching also works for variable usagesusages = function.code_block.get_variable_usages("config", fuzzy_match=True)# And for renaming variablesfunction.code_block.rename_variable_usages("config", "settings", fuzzy_match=True)# Renames: config -> settings, app_config -> app_settings, config_settings -> settings_settings
Be careful with fuzzy matching when renaming variables, as it will replace the
matched substring in all variable names. This might lead to unintended renames
like config_settings becoming settings_settings.