Skip to main content

API reference

Structural search and rewrite for Python source: declarative ast-grep pattern rules, LibCST matcher transforms for everything patterns can’t express, and tree-based symbol queries. Use this to edit code by structure (rename calls, move methods, rewrite APIs) where regexes break and ast loses comments.

notation: /why

astmap: ast-grep patterns

  • use: rewrite expressible as before pattern, after template; callable repl(match) -> str when new text needs computing
  • template $VAR the pattern didn’t capture: KeyError
from remold import *
fix_tests = astmap(
    ("test_fail(lambda: $BODY, contains=$MSG)", "with expect_fail(Exception, $MSG): $BODY"),
    ("test_fail(lambda: $BODY)",                "with expect_fail(Exception): $BODY"))
fix_tests("test_fail(lambda: f(x), contains='boom')  # tricky case\n")
# with expect_fail(Exception, 'boom'): f(x)  # tricky case

cstmap: LibCST matcher and a function

  • use: what patterns can’t express, comment- or whitespace-only changes too
  • approach: match structure in the tree, where matching is easy; write new code as a string, where comments and whitespace are just characters
  • fn str result: reparsed in place, so output always parses; several statements: siblings; '': statement deleted; CST node: full surgery
  • matchers: https://libcst.readthedocs.io/en/latest/matchers.html

Same transform; trivia='keep' keeps the comment:

tf = m.SimpleStatementLine(body=[m.Expr(m.Call(
    func=m.Name('test_fail'),
    args=[m.Arg(m.Lambda(body=m.SaveMatchedNode(m.DoNotCare(), 'body'))),
          m.Arg(keyword=m.Name('contains'), value=m.SaveMatchedNode(m.DoNotCare(), 'msg'))]))])
def fix(node, caps): return f"with expect_fail(Exception, {code(caps['msg'])}): {code(caps['body'])}"
cstmap(tf, fix)("test_fail(lambda: f(x), contains='boom')  # tricky case\n")
  • trivia='given': you place trivia, e.g. a statement’s trailing comment (node.trailing_whitespace.comment) moved above it: return f"{code(c)}\n{new}" if c else new

Comments and layout

  • param comment: travels with its param (code(p)); comment after def ...:: fd.body.header.comment
  • where LibCST keeps anything else: whereis(snippet, *frags); copy the paths into fn /no searching node docs
sig = "def f(foo, # hey\n      bam, # gg\n      bar): # ho\n    pass\n"
whereis(sig, 'foo', '# ho', '# hey')
# {'foo': ['.body[0].params.params[0].name'], '# ho': ['.body[0].body.header.comment', ...],
#  '# hey': ['.body[0].params.params[0].comma.whitespace_after.first_line.comment', ...]}

Layout-only change, one param per line:

def fix(fd, _):
    ps = [code(p).strip() for p in fd.params.params]
    c = fd.body.header.comment
    if c: ps[-1] = f"{ps[-1]} {code(c)}"
    return f"def {fd.name.value}(\n    " + "\n    ".join(ps) + "\n):" + code(fd.body.with_changes(header=cst.TrailingWhitespace()))
cstmap(m.FunctionDef(), fix, trivia='given')(sig)
# def f(
#     foo, # hey
#     bam, # gg
#     bar # ho
# ):
#     pass

Moving code across depths

  • returned string: parsed as its own module, statements spliced in; LibCST indentation is depth, not columns (statement lines, bracket continuations, comment lines): code written at any depth lands at the target depth, in target’s default_indent; multiline string contents never re-indented /that would change the program
  • move code: match the enclosing node (e.g. ClassDef), return the whole new arrangement /matching the FunctionDef replaces it in place, still inside the class

Method f → top-level fastcore @patch function:

def fix(cd, _):
    fs = [s for s in cd.body.body if m.matches(s, m.FunctionDef(name=m.Name('f')))]
    if not fs: return None
    fd = fs[0]
    rest = cd.with_changes(body=cd.body.with_changes(body=[s for s in cd.body.body if s is not fd]))
    p1 = code(fd.params.params[0]).strip().rstrip(',')
    ps = ', '.join([f'{p1}:{cd.name.value}'] + [code(p).strip().rstrip(',') for p in fd.params.params[1:]])
    return f"{code(rest)}\n@patch\ndef {fd.name.value}({ps}):{code(fd.body)}"
src = "class A:\n    def __init__(self): self.x = 1\n\n    def f(self, n): # add `n` to `x`\n        y = self.x+n\n        return y\n"
cstmap(m.ClassDef(), fix, trivia='given')(src)
  • result: class A without f, then @patch def f(self:A, n): # addntox`, body dedented a level;code(fd.body)` carried body and def-line comment

Finding

  • where a short name is defined: symdefs, any binding syntax (unpacking, for, with ... as, walrus, imports, def, class) /text search needs a regex per binding syntax, floods on two-letter names
  • symdefs, symrefs: unparseable source → empty set /safe to map over mixed content unguarded

Pattern transforms

Use astmap when a rewrite fits an ast-grep before/after pattern, and astfind to collect matching source spans without rewriting.

astmap

def astmap(
    *rules:tuple[str, typing.Union[str, typing.Callable]], # `(pattern, repl)` pairs where `repl` is a `$VAR` template or `callable(match) -> str`
)->Callable[[str], str]: # Composable `src -> src` source transform

Return a str -> str transform applying ast-grep pattern rules in order, reparsing between rules.

Raises KeyError if a template references a $VAR not captured by its pattern.

fix = astmap(("test_fail(lambda: $BODY)", "with expect_fail(Exception): $BODY"))
assert fix("test_fail(lambda: f(x))  # keep\n") == "with expect_fail(Exception): f(x)  # keep\n"

astfind

def astfind(
    src:str, # Python source text to search
    pattern:str, # ast-grep pattern, e.g. `"save($$$, ts=$_)"`
)->list[str]: # Matching source substrings in appearance order

Return the source text of each ast-grep pattern match in src.

CST transforms

Use cstmap for structural, layout, or comment-aware rewrites that pattern rules cannot express; render nodes with code and discover LibCST attribute paths with whereis.

cstmap

def cstmap(
    matcher, # `libcst.matchers` matcher; `m.SaveMatchedNode` captures arrive in `fn`'s second arg
    fn:Callable, # `fn(node, caps)` returning `None` (unchanged), a `str` (reparsed in place), or a CST node
    trivia:str='keep', # `'keep'` carries leading lines and trailing comment; `'given'` takes `fn`'s output verbatim
)->Callable[[str], str]: # Composable `src -> src` source transform

Return a str -> str transform replacing every LibCST node matching matcher with fn’s result.

code

def code(
    node:libcst._nodes.base.CSTNode, # LibCST node to render
)->str: # Exact source text including trivia

Render source text for LibCST node, preserving comments and whitespace.

whereis

def whereis(
    src:str, # Python source snippet to inspect
    *frags:str, # Source fragments to locate (e.g. `'foo'`, `'# note'`)
    contains:bool=False, # Match nodes containing `frag` rather than equaling it
)->dict[str, list[str]]: # `{frag: [attr_paths...]}` ordered deepest node first

Return the LibCST attribute paths where each fragment lives, deepest node first.

Symbol queries

Inspect top-level bindings and referenced names across any Python binding syntax; both return an empty set when src does not parse.

symdefs

def symdefs(
    src:str, # Python source text
)->set[str]: # Names bound in `src`'s top-level scope (empty set on `SyntaxError`)

Return all names bound in src’s top-level scope across assignments, imports, loops, def, class, and match.

assert symdefs("x, *rest = items\ndef helper(): pass\n") == {'x', 'rest', 'helper'}

symrefs

def symrefs(
    src:str, # Python source text
)->set[str]: # Names referenced anywhere in `src` (empty set on `SyntaxError`)

Return all names loaded anywhere in src (empty set if src does not parse).