Imran's Blog
Stuff I feel like blogging about.

Python and multiline lambdas

Posted on

The title of this post should be "Shut up about python and multi-line lambdas". I browse HackerNews a bit more than I should, if I'm being honest. Every now and again there will be a post involving python on the front page. Predictably there will always be (at least) one person in the comments moaning about the lack of multi-line lambdas and how it's holding python back from being a "real" language.

In python the lambda keyword is syntactic sugar. There's no difference between a one line function and a lambda. Here is the docs on lambdas:

Let's take a look at this using the python interpreter:

>>> def func1(a):
...     return a * a
>>> func2 = lambda a : a * a
>>> from dis import dis
>>> dis(func1)
  2           0 LOAD_FAST                0 (a)
              2 LOAD_FAST                0 (a)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE
>>> dis(func2)
  1           0 LOAD_FAST                0 (a)
              2 LOAD_FAST                0 (a)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE

Look at that, they are the same. They even have the same bytecode.

Keeping in mind that functions are first class objects in python, it should be pretty easy to have a multi-line "lambda":

def some_func(some_list):
    def multiline_lambda(x):
        temp = x + 1
        other_var = other_func(x)
        return temp + other_var

    r = map(multiline_lambda, some_list)

Then why, pray tell, does python have all these functional words and concepts without being "properly" functional? Just to appeal to the masses, which is something Guido van Rossum regrets