Skip to content

Instantly share code, notes, and snippets.

@wonderful-panda
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save wonderful-panda/8a22b74248a60cc8bb22 to your computer and use it in GitHub Desktop.

Select an option

Save wonderful-panda/8a22b74248a60cc8bb22 to your computer and use it in GitHub Desktop.
# coding: utf-8
import ast
class _MakeFunction(ast.NodeTransformer):
def __init__(self, name, args, body):
self.name = name
self.args = args
self.body = body
def run(self):
template = 'def {self.name}({self.args}): pass'.format(self=self)
template_ast = ast.parse(template, mode='exec')
return self.visit(template_ast)
def visit_Pass(self, node):
return ast.parse(self.body, mode='exec').body
class _ReturnLastResult(ast.NodeTransformer):
def visit_FunctionDef(self, node):
self.generic_visit(node)
retval_assign = \
ast.Assign(targets=[ast.Name(id='_retval_', ctx=ast.Store())],
value=ast.NameConstant(value=None))
retval_return = \
ast.Return(value=ast.Name(id='_retval_', ctx=ast.Load()))
node.body.insert(0, retval_assign)
node.body.append(retval_return)
return ast.fix_missing_locations(node)
def visit_Expr(self, node):
target = ast.Name(id='_retval_', ctx=ast.Store())
assign = ast.copy_location(
ast.Assign(targets=[target], value=node.value), node)
return assign
def functionize(name, args, body):
functionized_ast = \
_ReturnLastResult().visit(_MakeFunction(name, args, body).run())
return compile(functionized_ast, '<string>', mode='exec')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment