Skip to content

Instantly share code, notes, and snippets.

@jph00
Last active May 25, 2024 02:15
Show Gist options
  • Save jph00/3fcc91d4dc65441b1208d5f7a54934a7 to your computer and use it in GitHub Desktop.
Save jph00/3fcc91d4dc65441b1208d5f7a54934a7 to your computer and use it in GitHub Desktop.
Function to transform each node of `tree` matching types in `names` by passing them to `func`
import ast
from fastcore.utils import *
from fastcore.utils import _get_class
def tfm_ast(tree:ast.AST, func:callable, *names, **kwargs):
"Transform each node of `tree` by passing it to `func`"
def f(self, node):
res = func(node, **kwargs)
return res if res else node
d = {'visit_'+nm:f for nm in names}
res = _get_class('TmpVisitor', sup=ast.NodeTransformer, **d)().visit(tree)
ast.fix_missing_locations(res)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment