-
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
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 builtinisinstance function.
Adding Statements
Functions and Files support .prepend_statement(…) and .add_statement(…) to add statements to the symbol.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 anif block or a try/catch statement.
Codegen supports this functionality with the Editable.is_wrapped_in(…) method.
.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.
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:When reducing conditions, Codegen automatically handles the restructuring of
elif/else chains and preserves the correct control flow.