Codegen enables traversing and manipulating collections through the List and Dict classes.

These APIs work consistently across Python and TypeScript while preserving formatting and structure.

Core Concepts

The List and Dict classes provide a consistent interface for working with ordered sequences of elements. Key features include:

  • Standard sequence operations (indexing, length, iteration)
  • Automatic formatting preservation
  • Safe modification operations
  • Language-agnostic behavior
  • Comment and whitespace preservation

Collections handle:

  • Proper indentation
  • Delimiters (commas, newlines)
  • Multi-line formatting
  • Leading/trailing whitespace
  • Nested structures

List Operations

Lists in both Python and TypeScript can be manipulated using the same APIs:

# Basic operations
items_list = file.get_symbol("items").value  # Get list value
first = items_list[0]        # Access elements
length = len(items_list)     # Get length
items_list[0] = "new"       # Modify element
items_list.append("d")      # Add to end
items_list.insert(1, "x")   # Insert at position
del items_list[1]           # Remove element

# Iteration
for item in items_list:
    print(item.source)

# Bulk operations
items_list.clear()          # Remove all elements

Single vs Multi-line Lists

Collections automatically preserve formatting:

# Source code:
items = [a, b, c]
config = [
    "debug",
    "verbose",
    "trace",
]

# Manipulation code:
items_list = file.get_symbol("items").value
items_list.append("d")    # Adds new element

config_list = file.get_symbol("config").value
config_list.append("info")  # Adds with formatting

# Result:
items = [a, b, c, d]
config = [
    "debug",
    "verbose",
    "trace",
    "info",
]

Dictionary Operations

Dictionaries provide a similar consistent interface:

# Basic operations
settings = file.get_symbol("settings").value  # Get dict value
value = settings["key"]     # Get value
settings["key"] = "value"   # Set value
del settings["key"]         # Remove key
has_key = "key" in settings # Check existence

# Iteration
for key in settings:
    print(f"{key}: {settings[key]}")

# Bulk operations
settings.clear()           # Remove all entries

Was this page helpful?