PyFile
SourceFile representation for Python codebase
View source on GitHub
Inherits from
PyHasBlock, SourceFile, HasBlock, Usable, File, Expression, Importable, Editable, HasName
Attributes
classes
Returns all Classes in the file.
code_block
Represents the block of code contained in the file.
content
Returns the content of the file as a UTF-8 encoded string.
decorators
Returns a list of decorators associated with this symbol.
directory
Returns the directory that contains this file.
docstring
Gets the function's docstring.
extended
Returns a SymbolGroup of all extended nodes associated with this element.
extended_source
Returns the source text representation of all extended nodes.
extension
Returns the file extension.
file
A property that returns the file object for non-source files.
file_path
The relative file path as a string.
filepath
Retrieves the file path of the file that this Editable instance belongs to.
full_name
Returns the full name of the object, including the namespace path.
function_calls
Returns all function calls within the code block and its decorators.
functions
Returns all Functions in the file.
global_vars
Returns all GlobalVars in the file.
import_module_name
Returns the module name that this file gets imported as.
import_statements
Returns all ImportStatements in the file, where each import statement can contain
importers
Returns all imports that directly imports this file as a module.
imports
List of all Imports in this file.
inbound_imports
Returns all imports that are importing symbols contained in this file.
is_binary
Indicates whether the file contains binary data.
is_decorated
Returns whether the symbol is decorated with decorators.
name
Retrieves the base name of the object without namespace prefixes.
owners
Returns the CODEOWNERS of the file.
parent
The parent node of this Editable instance.
parent_class
Find the class this node is contained in
parent_function
Find the function this node is contained in
parent_statement
Find the statement this node is contained in
path
The absolute path of the file as a Path object.
programming_language
The programming language of the file. Set to ProgrammingLanguage.PYTHON.
resolved_value
Returns the resolved type of an Expression.
source
Text representation of the Editable instance.
start_byte
Returns the starting byte position of a file in its content.
symbols_sorted_topologically
Returns all Symbols in the file, sorted topologically (parents first). Robust to
variable_usages
Returns Editables for all TreeSitter node instances of variable usages within this node's
Methods
add_decorator
Adds a decorator to a function or method.
View source on GitHub
Parameters
new_decoratorrequiredThe decorator to add, including the '@' symbol.
skip_if_existsdefault: FalseIf True, skips adding if the decorator exists.
Returns
True if the decorator was added, False if skipped.
add_import
Adds an import to the file.
View source on GitHub
Parameters
imprequiredEither a Symbol to import or a string representation of an import statement.
aliasdefault: NoneOptional alias for the imported symbol. Only used when imp is a Symbol. Defaults to None.
import_typedefault: ImportType.UNKNOWNThe type of import to use. Only used when imp is a Symbol. Defaults to ImportType.UNKNOWN.
is_type_importdefault: FalseWhether this is a type-only import. Only used when imp is a Symbol. Defaults to False.
Returns
The existing import for the symbol if found, otherwise None.
add_symbol
Adds symbol to the file.
View source on GitHub
Parameters
symbolrequiredThe symbol to add to the file.
should_exportdefault: TrueWhether to export the symbol. Defaults to True.
Returns
The existing symbol if it already exists in the file or None if it was added.
add_symbol_from_source
Adds a symbol to a file from a string representation.
View source on GitHub
Parameters
sourcerequiredString representation of the symbol to be added. This should be valid source code for
Returns
The symbol is added directly to the file's content.
ancestors
Find all ancestors of the node of the given type. Does not return itself
View source on GitHub
Returns
dependencies
Returns a list of symbols that this symbol depends on.
View source on GitHub
Parameters
usage_typesdefault: UsageType.DIRECTThe types of dependencies to search for. Defaults to UsageType.DIRECT.
max_depthdefault: NoneMaximum depth to traverse in the dependency graph. If provided, will recursively collect
Returns
A list of symbols and imports that this symbol depends on, sorted by file location.
edit
Replace the source of this file with new_src.
View source on GitHub
Parameters
new_srcrequiredThe new source text to replace the current text with.
fix_indentationdefault: FalseIf True, adjusts the indentation of new_src to match the current
prioritydefault: 0The priority of the edit transaction. Higher priority edits are
dedupedefault: TrueIf True, deduplicates identical transactions. Defaults to True.
Returns
find
Find and return matching nodes or substrings within an Editable instance.
View source on GitHub
Parameters
strings_to_matchrequiredOne or more strings to search for.
exactdefault: FalseIf True, only return nodes whose source exactly matches one of the strings_to_match.
Returns
A list of Editable instances that match the search criteria.
find_by_byte_range
Finds all editable objects that overlap with the given byte range in the file.
View source on GitHub
Parameters
rangerequiredThe byte range to search within the file.
Returns
A list of all Editable objects that overlap with the given range.
find_string_literals
Returns a list of string literals within this node's source that match any of the given
View source on GitHub
Parameters
strings_to_matchrequiredA list of strings to search for in string literals.
fuzzy_matchdefault: FalseIf True, matches substrings within string literals. If False, only matches exact strings. Defaults to False.
Returns
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.
View source on GitHub
Returns
get_class
Returns a specific Class by full name. Returns None if not found.
View source on GitHub
Parameters
namerequiredThe full name of the class to search for.
Returns
The matching Class object if found, None otherwise.
get_extensions
Returns the file extensions associated with Python files.
View source on GitHub
Returns
A list containing '.py' as the only Python file extension.
get_function
Returns a specific Function by name.
View source on GitHub
Parameters
namerequiredThe name of the function to find.
Returns
The matching Function object if found, None otherwise.
get_global_var
Returns a specific global var by name. Returns None if not found.
View source on GitHub
Parameters
namerequiredThe name of the global variable to find.
Returns
The global variable if found, None otherwise.
get_import
Returns the import with matching alias. Returns None if not found.
View source on GitHub
Parameters
symbol_aliasrequiredThe alias name to search for. This can match either the direct import name or the aliased name.
Returns
The import statement with the matching alias if found, None otherwise.
get_import_insert_index
Determines the index position where a new import statement should be inserted in a Python file.
View source on GitHub
Parameters
import_stringrequiredThe import statement to be inserted.
Returns
The index where the import should be inserted. Returns 0 for future imports or if there are no existing imports after future imports. Returns None if there are no imports in the file.
get_import_string
Generates an import string for a symbol.
View source on GitHub
Parameters
aliasdefault: NoneAlias to use for the imported symbol. Defaults to None.
moduledefault: NoneModule path to import from. If None, uses module name from source. Defaults to None.
import_typedefault: ImportType.UNKNOWNType of import statement to generate. Defaults to ImportType.UNKNOWN.
is_type_importdefault: FalseWhether this is a type import. Currently unused. Defaults to False.
Returns
A formatted import string in the form of 'from {module} import {symbol}' with optional alias or wildcard syntax.
get_name
Returns the name node of the object.
View source on GitHub
Returns
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_symbol
Gets a symbol by its name from the file.
View source on GitHub
Parameters
namerequiredThe name of the symbol to find.
Returns
The found symbol, or None if not found.
get_variable_usages
Returns Editables for all TreeSitter nodes corresponding to instances of variable usage
View source on GitHub
Parameters
var_namerequiredThe variable name to search for.
fuzzy_matchdefault: FalseIf True, matches variables where var_name is a substring. If False, requires exact match. Defaults to False.
Returns
List of Editable objects representing variable usage nodes matching the given name.
has_import
Returns True if the file has an import with the given alias.
View source on GitHub
Parameters
symbol_aliasrequiredThe alias to check for in the import statements.
Returns
True if an import with the given alias exists, False otherwise.
insert_after
Inserts code after this node.
View source on GitHub
Parameters
new_srcrequiredThe source code to insert after this node.
fix_indentationdefault: FalseWhether to adjust the indentation of new_src to match the current node. Defaults to False.
newlinedefault: TrueWhether to add a newline before the new_src. Defaults to True.
prioritydefault: 0Priority of the insertion transaction. Defaults to 0.
dedupedefault: TrueWhether to deduplicate identical transactions. Defaults to True.
Returns
insert_before
Inserts text before this node's source with optional indentation and newline handling.
View source on GitHub
Parameters
new_srcrequiredThe text to insert before this node.
fix_indentationdefault: FalseWhether to fix the indentation of new_src to match the current node. Defaults to False.
newlinedefault: TrueWhether to add a newline after new_src. Defaults to True.
prioritydefault: 0Transaction priority for managing multiple edits. Defaults to 0.
dedupedefault: TrueWhether to deduplicate identical transactions. Defaults to True.
Returns
is_child_of
Checks if this node is a descendant of the given editable instance in the AST.
View source on GitHub
Returns
is_wrapped_in
Check if this node is contained another node of the given class
View source on GitHub
Returns
parent_of_type
Find the first ancestor of the node of the given type. Does not return itself
View source on GitHub
Returns
parent_of_types
Find the first ancestor of the node of the given type. Does not return itself
View source on GitHub
Returns
reduce_condition
Reduces an editable to the following condition
View source on GitHub
Returns
remove
Removes the file from the file system and graph.
View source on GitHub
Returns
rename
Renames a symbol and updates all its references in the codebase.
View source on GitHub
Parameters
new_namerequiredThe new name for the symbol.
prioritydefault: 0Priority of the edit operation. Defaults to 0.
Returns
A tuple containing the file node ID and the new node ID of the renamed symbol.
replace
Replace occurrences of text in the file.
View source on GitHub
Parameters
oldrequiredThe text to be replaced.
newrequiredThe text to replace with.
countdefault: -1Maximum number of replacements to make. -1 means replace all occurrences.
is_regexdefault: FalseIf True, treat 'old' as a regular expression pattern.
prioritydefault: 0The priority of the edit transaction. Higher priority edits are
Returns
List of affected Editable objects. For non-source files, always returns an empty list since they don't have Editable sub-components.
search
Returns a list of all regex match of regex_pattern, similar to python's re.search().
View source on GitHub
Parameters
regex_patternrequiredThe regular expression pattern to search for.
include_stringsdefault: TrueWhen False, excludes the contents of string literals from the search. Defaults to True.
include_commentsdefault: TrueWhen False, excludes the contents of comments from the search. Defaults to True.
Returns
A list of Editable objects corresponding to the matches found.
set_docstring
Sets or updates a docstring for a Python function or class.
View source on GitHub
Parameters
docstringrequiredThe docstring content to set.
auto_formatdefault: TrueWhether to format the text into a proper docstring format. Defaults to True.
clean_formatdefault: TrueWhether to clean and normalize the docstring format before insertion. Defaults to True.
force_multilinedefault: FalseWhether to force single-line comments to be converted to multi-line format. Defaults to False.
Returns
set_name
Sets the name of a code element.
View source on GitHub
Parameters
namerequiredThe new name to set for the object.
Returns
symbol_can_be_added
Checks if a Python symbol can be added to this Python source file.
View source on GitHub
Parameters
symbolrequiredThe Python symbol to check for compatibility with this file.
Returns
Always returns True as Python files can contain any Python symbol type.
symbol_usages
Returns a list of symbols that use or import the exportable object.
View source on GitHub
Parameters
usage_typesdefault: NoneThe types of usages to search for. Defaults to any.
Returns
A list of symbols that use or import the exportable object.
symbols
Returns all Symbols in the file, sorted by position in the file.
View source on GitHub
Returns
A list of all top-level symbols in the file, sorted by their position in the file. Symbols can be one of the following types: - Symbol: Base symbol class - TClass: Class definition - TFunction: Function definition - TGlobalVar: Global variable assignment - TInterface: Interface definition
update_filepath
Renames the file and updates all imports to point to the new location.
View source on GitHub
Parameters
new_filepathrequiredThe new filepath to move the file to.
Returns
usages
Returns a list of usages of the exportable object.
View source on GitHub
Parameters
usage_typesdefault: NoneSpecifies which types of usages to include in the results. Default is any usages.
Returns
A sorted list of Usage objects representing where this exportable is used, ordered by source location in reverse.