Last active
September 16, 2019 08:48
-
-
Save tritium21/b259955667759312d06e5fe97fd0dfe4 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 | |
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