Skip to content

Instantly share code, notes, and snippets.

@akiross
Created October 5, 2023 17:13
Show Gist options
  • Save akiross/4b033a79a9544c31bc6a12c1694c325f to your computer and use it in GitHub Desktop.
Save akiross/4b033a79a9544c31bc6a12c1694c325f to your computer and use it in GitHub Desktop.
Example of using python AST module to produce some python code.
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