Skip to content

Instantly share code, notes, and snippets.

@tritium21
Last active September 16, 2019 08:48
Show Gist options
  • Save tritium21/b259955667759312d06e5fe97fd0dfe4 to your computer and use it in GitHub Desktop.
Save tritium21/b259955667759312d06e5fe97fd0dfe4 to your computer and use it in GitHub Desktop.
import ast
def bad_idea(op):
"""
When overcomplicated isn't complicated enough...
"""
OP_TABLE = {
'add': ast.Add,
'sub': ast.Sub,
}
tree = ast.Interactive(body=[
ast.FunctionDef(
name=op if op in OP_TABLE else 'add',
args=ast.arguments(
args=[
ast.arg(arg='x', annotation=None),
ast.arg(arg='y', annotation=None)
],
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[]
),
body=[ast.Return(
value=ast.BinOp(
left=ast.Name(id='x', ctx=ast.Load()),
op=OP_TABLE.get(op, 'add')(),
right=ast.Name(id='y', ctx=ast.Load())
)
)],
decorator_list=[],
returns=None
)]
)
tree = ast.fix_missing_locations(tree)
namespace = {}
exec(compile(tree, '<ast>', 'single'), {}, namespace)
return namespace.get(op, 'add')
if __name__ == '__main__':
print(bad_idea('add'))
print(bad_idea('sub'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment