Index ¦ Archives ¦ Atom

Adding multi-line lambdas to Python

At the risk of this blog becoming dedicated to "the worst things you can do in Python" I present to you: multiline lambdas in Python!

Implementation was simple:

import sys

def fun(string):
    frame = sys._getframe(1)
    out = {}
    locals = {}
    exec ("def __anon("+string) in locals, out
    return out['__anon']

It's not obvious how to use it from here, so here's a few examples:

from multilambda import fun

def test():
    other = 3
    callback = fun("""arg1, arg2):
        arg1 += 4
        return arg1 * arg2 + other
    print callback(10, 10) # should be 143

def test_nested(a1, a2):
    # just when you thought it couldn't get any worse
    fun("""a1, a2):
            print a1, a2, b
    """)(a1 + 2, a2 + 3)

test_nested(10, 10)

My inspiration came from CoffeeScript and Konira which is a Python DSL for unittests. However, instead of tokenizing and parsing some Python superset language into Python bytecode, I realized how easy just execing a string was.

Everything works as you might expect; you can even nest them inside of each other. Of course, your editor won't like it; and your functions won't be compiled in pyc files... oh and also it's a terrible hack that no one would ever actually use.

© Chad Selph. Built using Pelican. Theme by Giulio Fidente on github.