Last active
May 25, 2024 02:15
-
-
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`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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