Inherits from

PySymbol, Assignment, Symbol, HasValue, Typeable, Usable, Importable, Editable, Expression, HasName

Properties


comment

Returns the comment group associated with the symbol.

Retrieves and returns any comments associated with the symbol. These comments are typically located above or adjacent to the symbol in the source code.

Args: self: The symbol instance to retrieve comments for.

Returns: PyCommentGroup | None: A comment group object containing the symbol’s comments if they exist, None otherwise.

def comment(self) -> PyCommentGroup | None:
    ...

dependencies

Returns a list of symbols that this symbol depends on.

Returns a list of symbols (including imports) that this symbol directly depends on. The returned list is sorted by file location for consistent ordering.

Returns: list[Union[Symbol, Import]]: A list of symbols and imports that this symbol directly depends on, sorted by file location.

def dependencies(self) -> list[Union["Symbol", "Import"]]:
    ...

extended

Returns a SymbolGroup of all extended nodes associated with this element.

Creates a SymbolGroup that provides a common interface for editing all extended nodes, such as decorators, modifiers, and comments associated with the element.

Args: None

Returns: SymbolGroup: A group containing this node and its extended nodes that allows batch modification through a common interface.

def extended(self) -> SymbolGroup:
    ...

extended_nodes

Returns a list of Editable nodes associated with this symbol, including extended symbols.

Extended symbols include export, public, decorator, comments, and inline comments.

Args: self: The symbol instance.

Returns: list[Editable]: A list of Editable nodes containing the current symbol and its extended symbols, sorted in the correct order.

def extended_nodes(self) -> list[Editable]:
    ...

extended_source

Returns the source text representation of all extended nodes.

Gets the source text of all extended nodes combined. This property allows reading the source text of all extended nodes (e.g. decorators, export statements) associated with this node.

Returns: str: The combined source text of all extended nodes.

def extended_source(self) -> str:
    ...

file

The file object that this Editable instance belongs to.

Retrieves or caches the file object associated with this Editable instance.

Returns: File: The File object containing this Editable instance.

def file(self) -> SourceFile:
    ...

filepath

The file path of the file that this Editable instance belongs to.

Returns a string representing the absolute file path of the File that contains this Editable instance.

Returns: str: The absolute file path.

def filepath(self) -> str:
    ...

full_name

Returns the full name of the object, including the namespace path.

Returns the complete qualified name of an object, including any parent class or namespace paths. For class methods, this returns the parent class’s full name followed by the method name. For chained attributes (e.g., ‘a.b’), this returns the full chained name.

Args: None

Returns: str | None: The complete qualified name of the object. Returns None if no name is available. For class methods, returns ‘ParentClass.method_name’. For chained attributes, returns the full chain (e.g., ‘a.b’). For simple names, returns just the name.

def full_name(self) -> str | None:
    ...

function_calls

Returns a list of all function calls contained within this expression.

Traverses the extended nodes of this expression to find all function calls within it. This is useful for tasks like analyzing call patterns or renaming function invocations.

Returns: list[FunctionCall]: A list of FunctionCall objects representing all function calls contained within this expression.

def function_calls(self) -> list[FunctionCall]:
    ...

index

Returns the index of the assignment statement in its parent’s code block.

Returns: int: The 0-based index position of the assignment statement within its parent’s code block statements.

def index(self) -> int:
    ...

inline_comment

A property that retrieves the inline comment group associated with a symbol.

Retrieves any inline comments that are associated with this symbol. Inline comments are comments that appear on the same line as the code.

Args: None

Returns: PyCommentGroup | None: The inline comment group associated with the symbol, if one exists. Returns None if there are no inline comments.

def inline_comment(self) -> PyCommentGroup | None:
    ...

is_exported

Indicates whether a Python symbol is exported.

In Python, all symbols are exported by default, so this property always returns True.

Returns: bool: Always True, as Python symbols are exported by default.

def is_exported(self) -> bool:
    ...

is_local_variable

Determines if an assignment represents a local variable in the current scope.

A local variable is an assignment that:

  1. Is not a chained attribute (e.g., not self.x or obj.x)
  2. Is not in the global (file) scope

Returns: bool: True if the assignment is a local variable, False otherwise.

def is_local_variable(self) -> bool:
    ...

is_typed

Property indicating if a node has an explicit type annotation.

Checks whether the object has an explicit type annotation or is using a placeholder type.

Returns: bool: True if the object has an explicit type annotation, False if it is using a placeholder type.

def is_typed(self) -> bool:
    ...

name

Retrieves the name of the object excluding any namespace prefixes.

Returns the “base” name of the object without any namespace or module prefix. For instance, for an object ‘a.b’, this method returns ‘b’.

Returns: str | None: The base name of the object as a string, or None if there is no associated name node.

def name(self) -> str | None:
    ...

resolved_value

Returns the resolved type of an Expression.

Returns the inferred type of the expression. For example a function call’s resolved value will be it’s definition.

Returns: Union[Expression, list[Expression]]: The resolved expression type(s). Returns a single Expression if there is only one resolved type, or a list of Expressions if there are multiple resolved types. Returns self if the expression is not resolvable or has no resolved types.

def resolved_value(self) -> Expression | list[Expression]:
    ...

source

Returns the source code of the symbol.

Gets the source code of the symbol from its extended representation, which includes any comments, docstrings, access identifiers, or decorators.

Returns: str: The complete source code of the symbol including any extended nodes.

def source(self) -> str:
    ...

value

Gets the value node of the object.

Returns the value node of the object implementing the HasValue interface. This node can represent various types of values, such as list elements, dictionary values, or expressions.

Returns: Expression | None: The value node of the object. None if no value is set.

def value(self) -> Expression | None:
    ...

variable_usages

Returns Editables for all TreeSitter node instances of variable usages within this node’s scope.

This method finds all variable identifier nodes in the TreeSitter AST, excluding:

  • Function names in function calls
  • Import names in import statements
  • Property access identifiers (except the base object)
  • Keyword argument names (in Python and TypeScript)

This is useful for variable renaming and usage analysis within a scope.

Returns: list[Editable]: A list of Editable nodes representing variable usages. Each Editable corresponds to a TreeSitter node instance where the variable is referenced.

def variable_usages(self) -> list[Editable]:
    ...

Attributes


parent_statement

Returns the parent statement that contains this expression

parent_statement: Statement | None

type

The type annotation associated with this node

type: TType | TypePlaceholder[Self]

Methods


add_comment

Adds a new comment to the symbol.

Appends a comment to the symbol either adding it to an existing comment group or creating a new one.

Args: comment (str): The comment text to be added. auto_format (bool): Whether to automatically format the text into a proper comment format. Defaults to True. clean_format (bool): Whether to clean and normalize the comment text before adding. Defaults to True. comment_type (PyCommentType): The style of comment to add (e.g., single-line, multi-line). Defaults to PyCommentType.SINGLE_LINE.

Returns: None

Raises: None

def add_comment(self, comment: str, auto_format: bool = True, clean_format: bool = True, comment_type: PyCommentType = PyCommentType.SINGLE_LINE) -> None:
    ...

add_keyword

Insert a keyword in the appropriate place before this symbol if it doesn’t already exist.

This method adds a keyword (e.g., ‘public’, ‘async’, ‘static’) in the syntactically appropriate position relative to other keywords. If the keyword already exists, no action is taken.

Args: keyword (str): The keyword to be inserted. Must be a valid keyword in the language context.

Raises: AssertionError: If the provided keyword is not in the language’s valid keywords list.

def add_keyword(self, keyword: str):
    ...

edit

Replace the source of this node with new_src.

Edits the source code of this node by replacing it with the provided new source code. If specified, the indentation of the new source can be adjusted to match the current text’s indentation.

Args: new_src (str): The new source code to replace the current source with. fix_indentation (bool): If True, adjusts the indentation of new_src to match the current text’s indentation. Defaults to False. priority (int): The priority of this edit. Higher priority edits take precedence. Defaults to 0. dedupe (bool): If True, prevents duplicate edits. Defaults to True.

Returns: None

def edit(self, new_src: str, fix_indentation: bool = False, priority: int = 0, dedupe: bool = True) -> None:
    ...

find

Find and return matching nodes or substrings within an Editable instance.

This method searches through the extended_nodes of the Editable instance and returns all nodes or substrings that match the given search criteria.

Args: strings_to_match (Union[list[str], str]): One or more strings to search for. exact (bool): If True, only return nodes whose source exactly matches one of the strings_to_match. If False, return nodes that contain any of the strings_to_match as substrings. Defaults to False.

Returns: list[Editable]: A list of Editable instances that match the search criteria.

def find(self, strings_to_match: list[str] | str, *, exact: bool = False) -> list[Editable]:
    ...

find_string_literals

Returns a list of string literals within this node’s source that match any of the given strings.

Args: strings_to_match (list[str]): A list of strings to search for in string literals. fuzzy_match (bool): If True, matches substrings within string literals. If False, only matches exact strings. Defaults to False.

Returns: list[Editable]: A list of Editable objects representing the matching string literals.

def find_string_literals(self, strings_to_match: list[str], fuzzy_match: bool = False) -> list[Editable]:
    ...

flag

Adds a visual flag comment to the end of this Editable’s source text.

Flags this Editable by appending a comment with emoji flags at the end of its source text. This is useful for visually highlighting specific nodes in the source code during development and debugging.

Returns: None

def flag(self, **kwargs: Unpack[FlagKwargs]) -> CodeFlag[Self]:
    ...

from_named_expression

Creates a MultiExpression from a Python named expression.

Creates assignments from a named expression node (‘walrus operator’ :=) by parsing its name and value fields.

Args: ts_node (TSNode): The TreeSitter node representing the named expression. file_node_id (NodeId): The identifier of the file containing this node. G (CodebaseGraph): The codebase graph instance. parent (Parent): The parent node that contains this expression.

Returns: MultiExpression[Parent, PyAssignment]: A MultiExpression containing the assignments created from the named expression.

Raises: ValueError: If the provided ts_node is not of type ‘named_expression’.

def from_named_expression(cls, ts_node: TSNode, file_node_id: NodeId, G: CodebaseGraph, parent: PyAssignmentStatement) -> MultiExpression[PyAssignmentStatement, PyAssignment]:
    ...

get_import_string

Generates an import string for a Python symbol.

Returns a string representation of how to import this symbol, with support for different import types and aliasing.

Args: alias (str | None): Optional alias name for the import. If provided and different from symbol name, creates aliased import. module (str | None): Optional module name to import from. If not provided, uses the symbol’s file’s module name. import_type (ImportType): Type of import to generate. If WILDCARD, generates star import. Defaults to UNKNOWN. is_type_import (bool): Whether this is a type import. Currently unused. Defaults to False.

Returns: str: The formatted import string. Will be one of:

  • “from import * as ” (for WILDCARD imports)
  • “from import as ” (for aliased imports)
  • “from import ” (for standard imports)
def get_import_string(
        self,
        alias: str | None = None,
        module: str | None = None,
        import_type: ImportType = ImportType.UNKNOWN,
        is_type_import: bool = False,
    ) -> str:
    ...

get_name

Returns the Name node of the object.

Retrieves the name node of the object which can be used for modification operations.

Returns: Name | ChainedAttribute | None: The name node of the object. Can be a Name node for simple names, a ChainedAttribute for names with namespaces (e.g., a.b), or None if the object has no name.

def get_name(self) -> Name | ChainedAttribute | None:
    ...

get_variable_usages

Returns Editables for all TreeSitter nodes corresponding to instances of variable usage that matches the given variable name.

Retrieves a list of variable usages that match a specified name, with an option for fuzzy matching. By default, excludes property identifiers and argument keywords.

Args: var_name (str): The variable name to search for. fuzzy_match (bool): If True, matches variables where var_name is a substring. If False, requires exact match. Defaults to False.

Returns: list[Editable]: List of Editable objects representing variable usage nodes matching the given name.

def get_variable_usages(self, var_name: str, fuzzy_match: bool = False) -> list[Editable]:
    ...

insert_after

Inserts code after this node.

Args: new_src (str): The source code to insert after this node. fix_indentation (bool, optional): Whether to adjust the indentation of new_src to match the current node. Defaults to False. newline (bool, optional): Whether to add a newline before the new_src. Defaults to True. priority (int, optional): Priority of the insertion transaction. Defaults to 0. dedupe (bool, optional): Whether to deduplicate identical transactions. Defaults to True.

Returns: None

def insert_after(self, new_src: str, fix_indentation: bool = False, newline: bool = True, priority: int = 0, dedupe: bool = True) -> None:
    ...

insert_before

Inserts text before the current symbol node in the Abstract Syntax Tree.

Handles insertion of new source code before a symbol, with special handling for extended nodes like comments and decorators. The insertion can be done either before the symbol itself or before its extended nodes.

Args: new_src (str): The source code text to insert. fix_indentation (bool): Whether to adjust the indentation of new_src to match current text. Defaults to False. newline (bool): Whether to add a newline after insertion. Defaults to True. priority (int): Priority of this edit operation. Higher priority edits are applied first. Defaults to 0. dedupe (bool): Whether to remove duplicate insertions. Defaults to True. extended (bool): Whether to insert before extended nodes like comments and decorators. Defaults to True.

Returns: None

def insert_before(self, new_src: str, fix_indentation: bool = False, newline: bool = True, priority: int = 0, dedupe: bool = True, extended: bool = True) -> None:
    ...

is_wrapped_in

Check if this node is contained another node of the given class

def is_wrapped_in(self, cls: type[Expression]) -> bool:
    ...

json

def json(self, max_depth: int = 2, methods: bool = True) -> JSON:
    ...

local_usages

Retrieves all usages of the assigned variable within its code block scope.

Returns all instances where the variable defined in this Assignment is used within its code block. Only returns usages that occur after the assignment, excluding the usage in the assignment itself.

Returns: list[Editable[Statement]]: A sorted list of statement nodes where the variable is used.

Note: This method can be called as both a property or a method. If used as a property, it is equivalent to invoking it without arguments.

def local_usages(self) -> list[Editable[Statement]]:
    ...

move_to_file

Moves the given symbol to a new file and updates its imports and references.

This method moves a symbol to a new file and updates all references to that symbol throughout the codebase. The way imports are handled can be controlled via the strategy parameter.

Args: file (SourceFile): The destination file to move the symbol to. include_dependencies (bool): If True, moves all dependencies of the symbol to the new file. If False, adds imports for the dependencies. Defaults to True. strategy (str): The strategy to use for updating imports. Can be either ‘add_back_edge’ or ‘update_all_imports’. Defaults to ‘update_all_imports’.

  • ‘add_back_edge’: Moves the symbol and adds an import in the original file
  • ’update_all_imports’: Updates all imports and usages of the symbol to reference the new file

Returns: None

Raises: AssertionError: If an invalid strategy is provided.

def move_to_file(self, file: SourceFile, include_dependencies: bool = True, strategy: str = "update_all_imports") -> None:
    ...

reduce_condition

Simplifies an assignment expression by reducing it based on a boolean condition and updating all the usages.

Args: bool_condition (bool): The boolean value to reduce the condition to.

def reduce_condition(self, bool_condition: bool, node: Editable | None = None) -> None:
    ...

remove

Deletes this Node and its related extended nodes (e.g. decorators, comments).

Removes the current node and its extended nodes (e.g. decorators, comments) from the codebase. After removing the node, it handles cleanup of any surrounding formatting based on the context.

Args: delete_formatting (bool): Whether to delete surrounding whitespace and formatting. Defaults to True. priority (int): Priority of the removal transaction. Higher priority transactions are executed first. Defaults to 0. dedupe (bool): Whether to deduplicate removal transactions at the same location. Defaults to True.

Returns: None

def remove(self, delete_formatting: bool = True, priority: int = 0, dedupe: bool = True) -> None:
    ...

rename

Renames the symbol and all its references in the codebase.

Renames a symbol to a new name and updates all references to that symbol throughout the codebase, including imports and call sites.

Args: new_name (str): The new name for the symbol. priority (int): Priority of the edit operation. Defaults to 0.

Returns: tuple[NodeId, NodeId]: A tuple containing the file node ID and the new node ID of the renamed symbol.

def rename(self, new_name: str, priority: int = 0):
    ...

replace

Search and replace occurrences of text within this node’s source and its extended nodes.

This method performs string replacement similar to Python’s string.replace(), with support for regex patterns. It operates on both the main node and any extended nodes (e.g. decorators, exports).

Args: old (str): The text or pattern to search for. new (str): The text to replace matches with. count (int, optional): Maximum number of replacements to make. Defaults to -1 (replace all). is_regex (bool, optional): Whether to treat ‘old’ as a regex pattern. Defaults to False. priority (int, optional): Priority of the replacement operation. Defaults to 0.

Returns: int: The total number of replacements made.

Raises: ValueError: If there are multiple occurrences of the substring in a node’s source.

def replace(self, old: str, new: str, count: int = -1, is_regex: bool = False, priority: int = 0) -> int:
    ...

Returns a list of all regex match of regex_pattern, similar to python’s re.search().

Searches for matches of a regular expression pattern within the text of this node and its extended nodes.

Args: regex_pattern (str): The regular expression pattern to search for. include_strings (bool): When False, excludes the contents of string literals from the search. Defaults to True. include_comments (bool): When False, excludes the contents of comments from the search. Defaults to True.

Returns: list[Editable]: A list of Editable objects corresponding to the matches found.

def search(self, regex_pattern: str, include_strings: bool = True, include_comments: bool = True) -> list[Editable]:
    ...

set_comment

Sets a comment for the Python symbol.

Adds or modifies a comment associated with the Python symbol. If a comment already exists, it will be edited. If no comment exists, a new comment group will be created.

Args: comment (str): The comment text to be added or set. auto_format (bool, optional): If True, automatically formats the text as a comment. Defaults to True. clean_format (bool, optional): If True, cleans the format of the comment before inserting. Defaults to True. comment_type (PyCommentType, optional): Type of comment to add (e.g., single line, multi line). Defaults to PyCommentType.SINGLE_LINE.

Returns: None: This method modifies the symbol’s comment in place.

def set_comment(self, comment: str, auto_format: bool = True, clean_format: bool = True, comment_type: PyCommentType = PyCommentType.SINGLE_LINE) -> None:
    ...

set_inline_comment

Sets an inline comment to the symbol.

Adds or replaces an inline comment for a Python symbol. If an inline comment exists, it will be replaced with the new comment. If no inline comment exists, a new one will be created at the end of the line.

Args: comment (str): The inline comment text to add. auto_format (bool, optional): If True, formats the text into a proper inline comment with appropriate prefixes and spacing. Defaults to True. clean_format (bool, optional): If True, cleans the comment text before insertion by removing extra whitespace and comment markers. Defaults to True.

Returns: None

def set_inline_comment(self, comment: str, auto_format: bool = True, clean_format: bool = True) -> None:
    ...

set_name

Sets the name of a code element.

Modifies the name of the object’s underlying name node. Works with both simple names and chained attributes (e.g., ‘a.b’).

Args: name (str): The new name to set for the object.

Returns: None

def set_name(self, name: str) -> None:
    ...

set_type_annotation

Adds or updates a type annotation for the current assignment.

This method modifies an assignment statement to include a type annotation. If the assignment already has a type annotation, it will be overwritten with the new type. If no type annotation exists, one will be added between the assignment name and the equals sign.

Args: type_str (str): The type annotation to be added or updated.

Returns: None

def set_type_annotation(self, type_str: str) -> None:
    ...

set_value

Sets the value of an assignment expression.

Updates the value of an assignment expression. If the assignment doesn’t have an existing value, it adds one after the type annotation (if present) or after the variable name. If the assignment already has a value, it replaces the existing value.

Args: src (str): The source code string representing the new value to be assigned.

Returns: None

def set_value(self, src: str) -> None:
    ...

symbol_usages

Returns a list of symbols that use the exportable object or import it. Returns symbols that use this exportable object, including imports that import this exportable object. By default, returns all usages. This shows where this symbol is imported, but not where it is subsequently used.

Args: usage_types: The types of usages to search for. Defaults to any.

  • DIRECT: Direct uses of the symbol
  • CHAINED: Uses through method/attribute chains
  • INDIRECT: Uses through renamed imports
  • ALIASED: Uses through aliases

Returns: list[Import | Symbol | Export]: A list of symbols that use this exportable object, including imports that import it.

Note: This method can be called as both a property or a method. If used as a property, it is equivalent to invoking it without arguments.

def symbol_usages(self, usage_types: UsageType | None = None) -> list[Import | Symbol | Export]:
    ...

usages

Returns a list of usages of the exportable object.

Retrieves a list of all locations where the exportable object is used in the codebase. By default, returns all usages, such as imports or references within the same file.

Args: usage_types: Specifies which types of usages to include in the results. Default is any usages. (graph_sitter.core.dataclasses.usage.UsageType)

Returns: list[Usage]: A sorted list of Usage objects representing where this exportable is used, ordered by source location in reverse.

Raises: ValueError: If no usage types are specified or if only ALIASED and DIRECT types are specified together.

Note: This method can be called as both a property or a method. If used as a property, it is equivalent to invoking it without arguments.

def usages(self, usage_types: UsageType | None = None) -> list[Usage]:
    ...