Statements and Code Blocks
Codegen uses two classes to represent code structure at the highest level:
-
Statement: Represents a single line or block of code
- Can be assignments, imports, loops, conditionals, etc.
- Contains source code, dependencies, and type information
- May contain nested code blocks (like in functions or loops)
-
CodeBlock: A container for multiple Statements
- Found in files, functions, classes, and control flow blocks
- Provides APIs for analyzing and manipulating statements
- Handles scope, variables, and dependencies
Codegen provides rich APIs for working with code statements and blocks, allowing you to analyze and manipulate code structure at a granular level.
Working with Statements
Basic Usage
Every file, function, and class in Codegen has a CodeBlock that contains its statements:
Filtering Statements
Filter through statements using Python’s builtin isinstance
function.
Adding Statements
Functions and Files support .prepend_statement(…) and .add_statement(…) to add statements to the symbol.
See Adding Statements for details.
Working with Nested Structures
Frequently you will want to check if a statement is nested within another structure, for example if a statement is inside an if
block or a try/catch
statement.
Codegen supports this functionality with the Editable.is_wrapped_in(…) method.
Similarly, all Editable objects support the .parent_statement
, which can be used to navigate the statement hierarchy.
Wrapping and Unwrapping Statements
CodeBlocks support wrapping and unwrapping with the following APIs:
- .wrap(…) - allows you to wrap a statement in a new structure.
- .unwrap(…) - allows you to remove the wrapping structure while preserving the code block’s contents.
Both wrap
and unwrap
are potentially unsafe changes and will modify
business logic.
The unwrap()
method preserves the indentation of the code block’s contents
while removing the wrapping structure. This is useful for refactoring nested
code structures.
Statement Types
Codegen supports various statement types, each with specific APIs:
Import Statements / Export Statements
If/Else Statements
If/Else statements provide rich APIs for analyzing and manipulating conditional logic:
If blocks also support condition reduction, which can simplify conditional logic:
When reducing conditions, Codegen automatically handles the restructuring of elif/else chains and preserves the correct control flow.
Switch/Match Statements
While Statements
Assignment Statements
Working with Code Blocks
Code blocks provide several ways to analyze and manipulate their content:
Statement Access
Statement Dependencies
Parent-Child Relationships
Common Operations
Finding Statements
Analyzing Flow Control
Working with Functions
Was this page helpful?