PyFunction
Extends Function for Python codebases.
Inherits from
PyHasBlock, PySymbol, Function, HasBlock, Symbol, Callable, Expression, Usable, Editable, Importable, HasName
Properties
body
Returns the body of the function as a string.
Gets the source code of the function’s body, excluding the docstring if present.
Returns: str: The function’s body content as a string, with any docstring removed and whitespace stripped.
call_sites
Returns all call sites (invocations) of this callable in the codebase.
Finds all locations in the codebase where this callable is invoked/called. Call sites exclude imports, certain exports, and external references.
Returns: list[FunctionCall]: A list of FunctionCall objects representing each invocation of this callable. Returns empty list if the callable has no name.
comment
Retrieves the comment group associated with a Python symbol.
A read-only property that returns the non-inline comment group (if any) that is associated with this symbol. Comments are considered associated with a symbol if they appear immediately before the symbol’s definition.
Returns: PyCommentGroup | None: A comment group object containing the symbol’s comments, or None if no comments exist.
decorators
Returns a list of decorators associated with this symbol.
Retrieves all decorator nodes from the symbol’s parent TreeSitter node and converts them into PyDecorator objects.
Args: None
Returns: list[PyDecorator]: A list of PyDecorator objects representing the decorators on the symbol. Returns an empty list if the symbol is not decorated.
Note: This property should be used in conjunction with is_decorated to check if the symbol has any decorators.
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.
docstring
Gets the function’s docstring.
Retrieves the docstring of the function as a PyCommentGroup object. If the function has no docstring, returns None.
Returns: PyCommentGroup | None: The docstring of the function as a PyCommentGroup, or None if no docstring exists.
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.
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.
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.
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.
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.
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.
function_calls
Gets all function calls within the function and its parameters.
Retrieves all function calls that appear within this function’s body and within its parameter declarations, sorted by position in the file.
Args: None
Returns: list[FunctionCall]: A sorted list of all function calls within the function and its parameters. Function calls may appear multiple times in the list.
function_signature
Returns the function signature as a string.
Gets the string representation of the function’s signature, including name, parameters, and return type.
Args: None
Returns: str: A string containing the complete function signature including the function name, parameters (if any), return type annotation (if present), and a colon.
inferred_return_type
Gets the inferred type of the function from the language’s native language engine / compiler.
Only enabled for specific languages that support native type inference.
inline_comment
Returns the inline comment group associated with this symbol.
Retrieves any inline comments attached to this symbol. An inline comment appears on the same line as the code it comments on.
Args: self (PySymbol): The Python symbol to check for inline comments.
Returns: PyCommentGroup | None: A comment group containing the inline comments if they exist, None otherwise.
is_async
Returns True if the function is asynchronous.
A property that determines whether the function has been defined with the ‘async’ keyword.
Returns: bool: True if the function is asynchronous, False otherwise.
is_class_method
Indicates whether the current function is decorated with @classmethod.
Args: self: The PyFunction instance.
Returns: bool: True if the function is decorated with @classmethod, False otherwise.
is_constructor
Determines if the current function is a constructor method.
A constructor method is a special method associated with a class. This property checks if the function is both a class method and has a name that matches the class’s constructor keyword.
Returns: bool: True if the function is a constructor method of a class, False otherwise.
is_decorated
Returns whether the symbol is decorated with decorators.
Checks if the symbol has a parent and if that parent’s type is a decorated definition.
Returns: bool: True if the symbol has decorators, False otherwise.
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.
is_magic
Determines if a method is a magic method.
A magic method in Python is a method that starts and ends with double underscores, such as __init__
or __str__
.
This property checks if the current method’s name matches this pattern.
Returns: bool: True if the method is a magic method (name starts and ends with double underscores), False otherwise.
is_method
Returns whether the function is a method of a class.
Determines if this function is defined within a class context. It checks if the parent of the function is a Class.
Returns: bool: True if the function is a method within a class, False otherwise.
is_overload
Determines whether a function is decorated with an overload decorator.
Checks if the function has any of the following decorators:
- @overload
- @typing.overload
- @typing_extensions.overload
Returns: bool: True if function has an overload decorator, False otherwise.
is_private
Determines if a method is a private method.
Private methods in Python start with an underscore and are not magic methods.
Returns: bool: True if the method is private (starts with ’_’ and is not a magic method), False otherwise.
is_property
Determines if the function is a property.
Checks the decorators list to see if the function has a @property
or @cached_property
decorator.
Returns:
bool: True if the function has a @property
or @cached_property
decorator, False otherwise.
is_static_method
Determines if the function is a static method.
Checks the function’s decorators to determine if it is decorated with the @staticmethod decorator.
Returns: bool: True if the function is decorated with @staticmethod, False otherwise.
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.
nested_functions
Returns a list of nested functions defined within this function’s code block.
Retrieves all functions that are defined within the current function’s body. The functions are sorted by their position in the file.
Returns: list[TFunction]: A list of Function objects representing nested functions within this function’s body, sorted by position in the file.
parameters
Retrieves all parameters of a callable symbol.
This property provides access to all parameters of a callable symbol (function, class, decorator, or external module). Parameters are stored as a SymbolGroup containing Parameter objects.
Returns: SymbolGroup[TParameter, Self] | None: A group of Parameter objects representing the callable’s parameters, or None if the callable has no parameters.
resolved_value
Returns the resolved value of an Expression.
Returns the last assigned expression value if the expression is resolvable, otherwise returns itself. For example, if ‘b = a’ where ‘a = 1’, resolving ‘b’ returns 1.
Returns: Union[Expression, list[Expression]]: The resolved expression value(s). Returns a single Expression if there is only one resolved value, or a list of Expressions if there are multiple resolved values. Returns self if the expression is not resolvable or has no resolved types.
return_statements
Returns a list of all return statements within this function’s body.
Provides access to return statements in the function’s code block, which is useful for analyzing return patterns, identifying early returns, and examining return types.
Args: None
Returns: list[ReturnStatement]: A list of all return statements found within the function’s body.
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.
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.
Attributes
parent_statement
Returns the parent statement that contains this expression
return_type
the return type annotation of the function
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
add_decorator
Adds a decorator to a function or method.
Adds a new decorator to the symbol’s definition. The decorator is inserted before the first non-comment extended node with proper indentation.
Args: new_decorator (str): The decorator to add. Should be a complete decorator string including the ’@’ symbol. skip_if_exists (bool, optional): If True, will not add the decorator if it already exists. Defaults to False.
Returns: bool: True if the decorator was added, False if skipped due to existing decorator.
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.
add_statements
Adds statements to the end of a function body.
Adds the provided lines of code to the end of the function’s code block. The method handles proper indentation automatically.
Args: lines (str): The lines of code to be added at the end of the function body.
Returns: None
asyncify
Modifies the function to be asynchronous.
Converts a synchronous function to be asynchronous by adding the ‘async’ keyword to its definition if it is not already marked as asynchronous.
Returns: None
Note: This method has no effect if the function is already asynchronous.
call_graph_successors
Returns all function call definitions that are reachable from this callable.
Analyzes the callable’s implementation to find all function calls and their corresponding definitions. For classes, if a constructor exists, returns the call graph successors of the constructor; otherwise returns an empty list.
Args: include_classes (bool): If True, includes class definitions in the results. Defaults to True. include_external (bool): If True, includes external module definitions in the results. Defaults to True.
Returns: list[FunctionCallDefinition]: A list of FunctionCallDefinition objects, each containing a function call and its possible callable definitions (Functions, Classes, or ExternalModules based on include flags). Returns empty list for non-block symbols or classes without constructors.
commit
Commits any pending transactions for the current node to the codebase.
Commits only the transactions that affect the file this node belongs to. This is useful when you want to commit changes made to a specific node without committing all pending transactions in the codebase.
Args: None
Returns: None
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
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.
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.
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
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)
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.
get_parameter
Gets a specific parameter from the callable’s parameters list by name.
Args: name (str): The name of the parameter to retrieve.
Returns: TParameter | None: The parameter with the specified name, or None if no parameter with that name exists or if there are no parameters.
get_parameter_by_index
Returns the parameter at the given index.
Retrieves a parameter from the callable’s parameter list based on its positional index.
Args: index (int): The index of the parameter to retrieve.
Returns: TParameter | None: The parameter at the specified index, or None if the parameter list is empty or the index does not exist.
get_parameter_by_type
Retrieves a parameter from the callable by its type.
Searches through the callable’s parameters to find a parameter with the specified type.
Args: type (Symbol): The type to search for.
Returns: TParameter | None: The parameter with the specified type, or None if no parameter is found or if the callable has no parameters.
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.
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
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
insert_statements
Inserts lines of code into the function body at the specified index.
Adds the provided lines as statements within the function’s body at the given position. If index is 0, the lines will be prepended at the start of the function body.
Args: lines (str): The code lines to insert into the function body. index (int, optional): The position in the function body where the lines should be inserted. Defaults to 0.
Raises: ValueError: If the provided index is out of range for the function’s statements.
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.
prepend_statements
Prepends statements to the start of the function body.
Given a string of code statements, adds them at the beginning of the function body, right after any existing docstring. The method handles indentation automatically.
Args: lines (str): The code statements to prepend to the function body.
Returns: None: This method modifies the function in place.
reduce_condition
Reduces an editable to the following condition
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
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.
rename_local_variable
Renames a local variable and all its usages within a function body.
The method searches for matches of the old variable name within the function’s code block and replaces them with the new variable name. It excludes parameter names from being renamed.
Args: old_var_name (str): The current name of the local variable to be renamed. new_var_name (str): The new name to give to the local variable. fuzzy_match (bool, optional): If True, matches variable names that contain old_var_name. Defaults to False.
Returns: None: The method modifies the AST in place.
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.
search
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.
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.
set_docstring
Sets or updates a docstring for a Python function or class.
Updates the existing docstring if one exists, otherwise creates a new docstring. The docstring can be automatically formatted and cleaned before being set.
Args: docstring (str): The docstring content to set. auto_format (bool, optional): Whether to format the text into a proper docstring format. Defaults to True. clean_format (bool, optional): Whether to clean and normalize the docstring format before insertion. Defaults to True. force_multiline (bool, optional): Whether to force single-line comments to be converted to multi-line format. Defaults to False.
Returns: 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
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
set_return_type
Sets or modifies the return type annotation of a function.
Updates the function’s return type annotation by either modifying an existing return type or adding a new one. If an empty string is provided as the new return type, removes the existing return type annotation.
Args: new_return_type (str): The new return type annotation to set. Provide an empty string to remove the return type annotation.
Returns: 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.
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.
Was this page helpful?