Codegen uses a set of core behaviors that can be inherited by code elements. These behaviors provide consistent APIs across different types of symbols.

This guide explains the key behaviors and how to use them effectively.

Core Behaviors

  • HasName: For elements with names (functions, classes, variables)
  • HasValue: For elements with values (variables, parameters)
  • HasBlock: For elements containing code blocks (functions, classes)
  • Editable: For elements that can be safely modified (learn more)

Working with Names

The HasName behavior provides APIs for working with named elements:

# Access the name
print(function.name)  # Base name without namespace
print(function.full_name)  # Full qualified name with namespace

# Modify the name
function.set_name("new_name")  # Changes just the name
function.rename("new_name")    # Changes name and updates all usages

# Get the underlying name node
name_node = function.get_name()

Working with Values

The HasValue behavior provides APIs for elements that have values:

# Access the value
value = variable.value  # Gets the value Expression node
print(value.source)     # Gets the string content

# Modify the value
variable.set_value("new_value")

# Common patterns
if variable.value is not None:
    print(f"{variable.name} = {variable.value.source}")

Working with Code Blocks

The HasBlock behavior provides APIs for elements containing code:

# Access the code block
block = function.code_block
print(len(block.statements))  # Number of statements

# Work with decorators
for decorator in function.decorators:
    print(f"@{decorator.name}")

function.add_decorator("@deprecated")

# Access docstrings
print(function.docstring)
function.set_docstring("New documentation")

# Find function calls
for fcall in function.function_calls:
    print(f"Calls {fcall.name}")

Working with Attributes

The get_attribute method provides APIs for attribute access:

# Common patterns
class_attr = class_def.get_attribute("attribute_name")
if class_attr:
    print(f"Class variable value: {class_attr.value.source}")

Behavior Combinations

Many code elements inherit multiple behaviors. For example, a function typically has:

# Functions combine multiple behaviors
function = codebase.get_function("process_data")

# HasName behavior
print(function.name)
function.rename("process_input")

# HasBlock behavior
print(len(function.code_block.statements))
function.add_decorator("@timer")

# Editable behavior
function.edit("def process_input():\n    pass")

Was this page helpful?