Created
October 2, 2023 15:44
-
-
Save zachmullen/26ce5f5d42f2e084b726584c8e7b3501 to your computer and use it in GitHub Desktop.
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 | |
import sys | |
import inflection | |
class TransformDeclaredAttr(ast.NodeTransformer): | |
def visit_FunctionDef(self, node: ast.FunctionDef): | |
if 'declared_attr' in [dec.id for dec in node.decorator_list]: | |
assert len(node.body) == 1 | |
assert isinstance(node.body[0], ast.Return) | |
call = node.body[0].value | |
assert isinstance(call, ast.Call) | |
assert len(call.args) == 2 | |
assert isinstance(call.args[1], ast.Call) | |
new_name = inflection.underscore(node.name).lower() | |
return ast.Assign( | |
targets=[ast.Name(id=new_name, ctx=ast.Store())], | |
value=call.args[1], | |
lineno=node.lineno, | |
) | |
return self.generic_visit(node) | |
with open(sys.argv[1]) as file: | |
tree = ast.parse(file.read()) | |
new_tree = TransformDeclaredAttr().visit(tree) | |
print(ast.unparse(new_tree)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment