Use as a library
pyastgrep is structured internally to make it easy to use as a library as well as a CLI, with a clear separation of the different layers. For now, the following API is documented as public and we will strive to maintain backwards compatibility with it:
- pyastgrep.api.search_python_files(paths, expression)
Searches for files with AST matching the given XPath
expression
, in the givenpaths
.If
paths
contains directories, then all Python files in that directory and below will be found, but.gitignore
and other rules are used to ignore files and directories automatically.Returns an iterable of
Match
object, plus other objects.The other objects are used to indicate errors, usually things like a failure to parse a file that had a
.py
extension. The details of these other objects are not being documented yet, so use at own risk, and ensure that you filter the results by doing anisinstance
check for theMatch
objects.- Parameters:
paths (list[pathlib.Path]) – List of paths to search, which can be files or directories, of type
pathlib.Path
expression (str) – XPath expression
- Returns:
Iterable[Match | Any]
- class pyastgrep.api.Match
Represents a matched AST node. The public properties of this are:
- property path
The path of the file containing the match.
- Type:
- class pyastgrep.api.Position
For other things, we while we will try not to break things without good reason, at this point we are not documenting or guaranteeing API stability for these functions. Please contribute to the discussion if you have needs here.
Example
For example usage of search_python_files
, see the blog post pyastgrep and
custom linting.