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

Core Behaviors

These “behaviors” are implemented as inherited classes.

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
printS(block.source)

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")