Created
October 5, 2023 17:13
-
-
Save akiross/4b033a79a9544c31bc6a12c1694c325f to your computer and use it in GitHub Desktop.
Example of using python AST module to produce some python code.
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 json | |
import ast | |
from ast import ( | |
ClassDef, | |
FunctionDef, | |
arguments, | |
arg, | |
BinOp, | |
Name, | |
Add, | |
Sub, | |
Load, | |
Return, | |
) | |
# Read config | |
config = json.loads( | |
"""{ | |
"class": "FooBar", | |
"methods": ["add", "sub"] | |
}""" | |
) | |
ops = {"add": ast.Add, "sub": ast.Sub} | |
# Create class | |
code = ClassDef( | |
name=config["class"], | |
bases=[], | |
keywords=[], | |
body=[ | |
FunctionDef( | |
name=funz, | |
args=arguments( | |
posonlyargs=[], | |
args=[arg(arg="self"), arg(arg="one"), arg(arg="two")], | |
kwonlyargs=[], | |
kw_defaults=[], | |
defaults=[], | |
), | |
body=[ | |
Return( | |
value=BinOp( | |
left=Name(id="one", ctx=Load()), | |
op=ops[funz](), | |
right=Name(id="two", ctx=Load()), | |
) | |
) | |
], | |
decorator_list=[], | |
) | |
for funz in config["methods"] | |
], | |
decorator_list=[], | |
) | |
# Produce file (also count lines) | |
print(ast.unparse(ast.fix_missing_locations(code))) | |
# Santa's little exampler | |
# print( | |
# ast.dump( | |
# ast.parse( | |
# """class FooBar: | |
# def add(self, one, two): | |
# return one + two | |
# """ | |
# ), | |
# indent=4, | |
# ) | |
# ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment