Hacking the Python syntax (implicit return values)

Python provide some functional programming features. However, the return value of a function has to be explicit. You have to use the keyword return in order to tell the function to return a value. Else, the function will return None. In some languages, the last value of a function is the return value. I like this behavior and I would like to have that in Python too. It turns out, that it's possible to modify the language by hacking the code AST (abstract syntaxe tree). The code below transforms the last expression of a function into a return.

from compiler.ast import *
import compiler, inspect

def modify(f, alter):
    "Modify function f using alter and make the new function available"
    # get code and modify
    raw = compiler.parse(inspect.getsource(f))
    raw.node.nodes[0].getChildren()[5].nodes = alter(raw.node.nodes[0].getChildren()[5].nodes)
    # generate
    compiler.misc.set_filename("temp", raw)
    expr = compiler.pycodegen.ExpressionCodeGenerator(raw).getCode()
    eval(expr, f.func_globals)

def hack(nodes):
    "Transform the last node of the AST into a return"
    newnodes = []
    for node in nodes:
        newnodes += [node]
    last = newnodes[-1]
    if "Discard" in str(last):
        newnodes[-1] = Return(last.getChildren()[0])
    return newnodes

def square(x):
    x*x

modify(square, hack)
print square(3)