Codegen’s GraphSitter library parses all collections into structure similar to the built-in python datastructures they represent. This guide will walk you through the process modifying and using these structures.

Common use cases include:

  • Adding parameters to functions
  • Converting dictionaries to schemas
  • Appending to lists of arguments

Adding parameters to functions

Since parameters are a collection, you can call standard methods such as append to add new parameters to a function.

Inspecting the contents of a Dictionary

You can get the value of a dictionary to use in further modifications.

Converting dictionaries to schemas

You can convert dictionaries to schemas by modifying the value of a variable.

var = codebase.get_file("path/to/file.py").get_global_var("var_name")

# Convert its assignment to a Schema and excludes certain keys
var.set_value(f"Schema({", ".join(f"{k}={v}" for k, v in var.value.items() if k != "excluded")})")

Appending to a list of in an assignment

You can append to a list using standard methods. For example, to append to a list assigned to a global variable

Check if a collection contains an item

You can use python’s in operator to check if a collection contains a specific item. It checks if any contained item has the same source.

function = codebase.get_file("path/to/file.py").get_function("function_name")

# Check if the function has a decorator named "@cache"
if "@cache" in function.decorators:
    print(f"Function: {function.name} has a @cache decorator")