# Lambdas and functions in Python

In my last post, I discussed some ways to avoid nested code in Python and discussing the “*filter*” and “*map*” functions I mentioned the * lambda functions*.

After that article, some reader asked me to write a little more about this topic, so … here I am. :)

Let’s start with a mantra. If you want to know what something is, in Python, just use your REPL.

So, start the Python REPL and define a lambda:

```
1Python 3.6.2 |Anaconda custom (64-bit)| (default, Sep 19 2017, 08:03:39) [MSC v.1900 64 bit (AMD64)] on win32
2Type "help", "copyright", "credits" or "license" for more information.
3
4>>> my_lambda = lambda x: x+1
```

Now, try to ask Python what is “my_lambda”

```
1>>> print(my_lambda)
2<function <lambda> at 0x0000021D14663E18>
```

It turns out that a “lambda” is… just a function!

Basically, a lambda is just an anonymous function that can be used “inline” whenever your code expects to find a function. In Python, in fact, functions are first-class objects and that basically means that they can be used like any other objects. They can be passed to other functions, they can be assigned to a name, they can be returned from a function and so on.

So, in our first example, we just defined a function that takes an argument (x), sums the value 1 to the input argument, and returns the result of this operation.

What’s the name of the function? It has no name actually, and so I had to assign this anonymous function to the name “my_lambda” to be able to use it in my code.

Now I can hear some of you saying:

Why bother with this stuff? Why not just use a standard named function? Couldn’t I write something like this?

```
1>>> def my_sum_function(x):
2... return x+1
3...
4>>> print (my_sum_function)
5<function my_sum_function at 0x0000021D14D83E18>
```

Yes, you could actually… and I will tell you something more: you can pass this function as well to other functions.

In our example, if we use:

```
1>>> print(list(map(my_lambda, range(10)))) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

we get the same results of writing:

```
1>>> print(list(map(my_sum_function, range(10))))
2[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

So, why bother with lambda functions?

Well… it’s just a matter of style and readability, because as we will keep saying: readability counts (“The Zen Of Python”, rule #7).

## The case of the RPN Calculator

Let’s pretend that one of your customers asked you to create a program to simulate a “Reverse Polish Notation calculator” that they will install on all their employees' computers. You accept this work and get the specs for the program:

The program should be able to do all the basic operations (divide, sum, subtract, multiply), to find the square root of a number and to power to 2 a number. Obviously, you should be able to clear all the stack of the calculator or just to drop the last inserted number.

RPN Calculator for newbiesIf you already know what is a RPN calculator, skip this part. If you do not know what is the Reverse Polish Notation, but you are curious, just check this out. If you do not know anything about the Reverse Polish Notation and you want just a brief explanation to keep reading this article… go ahead. The Reverse Polish Notation was very relevant in 70’s and 80’s as Hewlett-Packard used it in their scientific calculators and I personally love this notation. Basically in a RPN calculator you have a “stack” where you put the operands with a LIFO (last in, first out) logic. Then, when you press the button to compute an operation, the calculator takes out from the stack all the operands that the operation ask for, compute the operation and put the result back to the stack. So, let’s do an example. You want the result of the operation 5 x 6. In a standard calc you would act this way:

- press 5
- press *
- press 6
- press = and on the display you get the result : 30. In a RPN calculator, you act this way:
- press 5
- press ENTER (and the number 5 is put on the stack)
- press 6
- press ENTER (and the number 6 is put on the stack)
- press *

Now, before pressing the ‘*' symbol your stack was like this: 5 6 - after pressing the ‘*' symbol, you find on the stack just the result: 30. That’s because the calculator knows that for a multiplication you need two operands, so it has “popped” the first value (6 — remember, it’s a stack, it’s LIFO), then it has “popped” the second value (5), it has executed the operation and put back the result (30) on the stack. RPN calculators are great since they do not need expressions to be parethesized and there’s more: they’re cool! :)

Now, you accepted the job and you have to start working, but since the deadline of the project is very tight, you decide to ask Max, your IT artist, of writing a GUI for the calculator and Peter, your new intern, of creating the “engine” of this calculator software.

Let’s focus on Peter’s work.

## Peter’s work

After a while, Peter comes proudly to you asserting he has finished coding the calculator engine.

And that’s what he has done so far:

```
1"""
2Engine class of the RPN Calculator
3"""
4
5import math
6
7class rpn_engine:
8 def __init__(self):
9 """ Constructor """
10 self.stack = []
11
12 def push(self, number):
13 """ push a value to the internal stack """
14 self.stack.append(number)
15
16 def pop(self):
17 """ pop a value from the stack """
18 try:
19 return self.stack.pop()
20 except IndexError:
21 pass # do not notify any error if the stack is empty...
22
23 def sum_two_numbers(self):
24 op2 = self.stack.pop()
25 op1 = self.stack.pop()
26 self.push(op1 + op2)
27
28 def subtract_two_numbers(self):
29 op2 = self.stack.pop()
30 op1 = self.stack.pop()
31 self.push(op1 - op2)
32
33 def multiply_two_numbers(self):
34 op2 = self.stack.pop()
35 op1 = self.stack.pop()
36 self.push(op1 * op2)
37
38 def divide_two_numbers(self):
39 op2 = self.stack.pop()
40 op1 = self.stack.pop()
41 self.push(op1 / op2)
42
43 def pow2_a_number(self):
44 op1 = self.stack.pop()
45 self.push(op1 * op1)
46
47 def sqrt_a_number(self):
48 op1 = self.stack.pop()
49 self.push(math.sqrt(op1))
50
51
52 def compute(self, operation):
53 """ compute an operation """
54
55 if operation == '+':
56 self.sum_two_numbers()
57
58 if operation == '-':
59 self.subtract_two_numbers()
60
61 if operation == '*':
62 self.multiply_two_numbers()
63
64 if operation == '/':
65 self.divide_two_numbers()
66
67 if operation == '^2':
68 self.pow2_a_number()
69
70 if operation == 'SQRT':
71 self.sqrt_a_number()
72
73 if operation == 'C':
74 self.stack.pop()
75
76 if operation == 'AC':
77 self.stack.clear()
```

In a moment he understands that you’re looking at him shocked and states: “*my code runs fine*”.

Now, let’s clarify one thing: Peter’s right. His code runs (so does a burning bus…). Nevertheless, his code sucks. That’s it.

So let’s have a look at how we can improve this “stuff”.

The first problem here is the code duplication. There’s a principle of software engineering that is called “DRY”. It stands for “Don’t Repeat Yourself”.

Peter has duplicated a lot of code because for every single function he has to get the operands, compute the operation and put the result back to the stack. Wouldn’t it be great if we could have a function that does exactly this job, computing the operation we request? How can we achieve this?

Well, it’s really simple actually, because as we said earlier… functions are first-class objects in Python! So, Peter’s code can be simplified a lot.

Let’s have a look at the functions we have to provide.

All the standard operations (divide, sum, add and multiply) needs two operands to be computed. The “sqrt” and the “pow2” functions need just one operand to be computed. The “C” (to drop the last item in the stack) and “AC” (to clear the stack) functions, don’t need any operand to be computed.

So, let’s rewrite Peter’s code this way:

```
1"""
2Engine class of the RPN Calculator
3"""
4
5import math
6
7class rpn_engine:
8 def __init__(self):
9 """ Constructor """
10 self.stack = []
11
12 def push(self, number):
13 """ push a value to the internal stack """
14 self.stack.append(number)
15
16 def pop(self):
17 """ pop a value from the stack """
18 try:
19 return self.stack.pop()
20 except IndexError:
21 pass # do not notify any error if the stack is empty...
22
23 def sum_two_numbers(self, op1, op2):
24 return op1 + op2
25
26 def subtract_two_numbers(self, op1, op2):
27 return op1 - op2
28
29 def multiply_two_numbers(self, op1, op2):
30 return op1 * op2
31
32 def divide_two_numbers(self, op1, op2):
33 return op1 / op2
34
35 def pow2_a_number(self, op1):
36 return op1 * op1
37
38 def sqrt_a_number(self, op1):
39 return math.sqrt(op1)
40
41
42 def compute(self, operation):
43 """ compute an operation """
44
45 if operation == '+':
46 self.compute_operation_with_two_operands(self.sum_two_numbers)
47
48 if operation == '-':
49 self.compute_operation_with_two_operands(self.subtract_two_numbers)
50
51 if operation == '*':
52 self.compute_operation_with_two_operands(self.multiply_two_numbers)
53
54 if operation == '/':
55 self.compute_operation_with_two_operands(self.divide_two_numbers)
56
57 if operation == '^2':
58 self.compute_operation_with_one_operand(self.pow2_a_number)
59
60 if operation == 'SQRT':
61 self.compute_operation_with_one_operand(self.sqrt_a_number)
62
63 if operation == 'C':
64 self.stack.pop()
65
66 if operation == 'AC':
67 self.stack.clear()
68
69 def compute_operation_with_two_operands(self, operation):
70 """ exec operations with two operands """
71 try:
72 if len(self.stack) < 2:
73 raise BaseException("Not enough operands on the stack")
74
75 op2 = self.stack.pop()
76 op1 = self.stack.pop()
77 result = operation(op1, op2)
78 self.push(result)
79 except BaseException as error:
80 print(error)
81
82 def compute_operation_with_one_operand(self, operation):
83 """ exec operations with one operand """
84 try:
85 op1 = self.stack.pop()
86 result = operation(op1)
87 self.push(result)
88 except BaseException as error:
89 print(error)
```

Isn’t it better? The duplicated code is far less than before and looks at the functions, all they do is to compute the operation and return the results. They are no longer in charge of getting operands and pushing the result to the stack, the readability of the code is definitely improved!

Now, looking at the code, the first thing I really hate is all the “ifs” in the compute function. Perhaps replacing them with a “switch” function… if only the switch function would exist in Python! :)

But we can do something better. Why don’t we create a *catalog* of the available functions and then we just use this catalog to decide which function to use?

Why don’t we use a *dictionary* for that?

Let’s try to modify our code again:

```
1"""
2Engine class of the RPN Calculator
3"""
4
5import math
6
7class rpn_engine:
8 def __init__(self):
9 """ Constructor """
10 self.stack = []
11 self.catalog = self.get_functions_catalog()
12
13 def get_functions_catalog(self):
14 return {"+": self.sum_two_numbers,
15 "-": self.subtract_two_numbers,
16 "*": self.multiply_two_numbers,
17 "/": self.divide_two_numbers,
18 "^2": self.pow2_a_number,
19 "SQRT": self.sqrt_a_number,
20 "C": self.stack.pop,
21 "AC": self.stack.clear}
22
23 def push(self, number):
24 """ push a value to the internal stack """
25 self.stack.append(number)
26
27 def pop(self):
28 """ pop a value from the stack """
29 try:
30 return self.stack.pop()
31 except IndexError:
32 pass # do not notify any error if the stack is empty...
33
34 def sum_two_numbers(self, op1, op2):
35 return op1 + op2
36
37 def subtract_two_numbers(self, op1, op2):
38 return op1 - op2
39
40 def multiply_two_numbers(self, op1, op2):
41 return op1 * op2
42
43 def divide_two_numbers(self, op1, op2):
44 return op1 / op2
45
46 def pow2_a_number(self, op1):
47 return op1 * op1
48
49 def sqrt_a_number(self, op1):
50 return math.sqrt(op1)
51
52
53 def compute(self, operation):
54 """ compute an operation """
55
56 if operation in ['+', '-', '*', '/']:
57 self.compute_operation_with_two_operands(self.catalog[operation])
58
59 if operation in ['^2', 'SQRT']:
60 self.compute_operation_with_one_operand(self.catalog[operation])
61
62 if operation in ['C', 'AC']:
63 self.compute_operation_with_no_operands(self.catalog[operation])
64
65 def compute_operation_with_two_operands(self, operation):
66 """ exec operations with two operands """
67 try:
68 if len(self.stack) < 2:
69 raise BaseException("Not enough operands on the stack")
70
71 op2 = self.stack.pop()
72 op1 = self.stack.pop()
73 result = operation(op1, op2)
74 self.push(result)
75 except BaseException as error:
76 print(error)
77
78 def compute_operation_with_one_operand(self, operation):
79 """ exec operations with one operand """
80 try:
81 op1 = self.stack.pop()
82 result = operation(op1)
83 self.push(result)
84 except BaseException as error:
85 print(error)
86
87 def compute_operation_with_no_operands(self, operation):
88 """ exec operations with no operands """
89 try:
90 operation()
91 except BaseException as error:
92 print(error)
```

Wow, almost all our “*if(s)*” are gone! And now we have a catalog of functions that we can expand as we want. So for example, if we need to implement a factorial function, we will just add the function to the catalog and implement a custom method in the code. That’s really good!

Even if …

It would be great to act only on the catalog, wouldn’t it? But wait… shouldn’t we talk about lambdas in this article?

Here’s where lambdas can be useful! We don’t need a standard defined function for a simple calc, we need just an inline lambda for that!

```
1"""
2Engine class of the RPN Calculator
3"""
4
5import math
6
7class rpn_engine:
8 def __init__(self):
9 """ Constructor """
10 self.stack = []
11 self.catalog = self.get_functions_catalog()
12
13 def get_functions_catalog(self):
14 return {"+": lambda x, y: x + y,
15 "-": lambda x, y: x - y,
16 "*": lambda x, y: x * y,
17 "/": lambda x, y: x / y,
18 "^2": lambda x: x * x,
19 "SQRT": lambda x: math.sqrt(x),
20 "C": self.stack.pop,
21 "AC": self.stack.clear}
22
23 def push(self, number):
24 """ push a value to the internal stack """
25 self.stack.append(number)
26
27 def pop(self):
28 """ pop a value from the stack """
29 try:
30 return self.stack.pop()
31 except IndexError:
32 pass # do not notify any error if the stack is empty...
33
34 def compute(self, operation):
35 """ compute an operation """
36
37 if operation in ['+', '-', '*', '/']:
38 self.compute_operation_with_two_operands(self.catalog[operation])
39
40 if operation in ['^2', 'SQRT']:
41 self.compute_operation_with_one_operand(self.catalog[operation])
42
43 if operation in ['C', 'AC']:
44 self.compute_operation_with_no_operands(self.catalog[operation])
45
46 def compute_operation_with_two_operands(self, operation):
47 """ exec operations with two operands """
48 try:
49 if len(self.stack) < 2:
50 raise BaseException("Not enough operands on the stack")
51
52 op2 = self.stack.pop()
53 op1 = self.stack.pop()
54 result = operation(op1, op2)
55 self.push(result)
56 except BaseException as error:
57 print(error)
58
59 def compute_operation_with_one_operand(self, operation):
60 """ exec operations with one operand """
61 try:
62 op1 = self.stack.pop()
63 result = operation(op1)
64 self.push(result)
65 except BaseException as error:
66 print(error)
67
68 def compute_operation_with_no_operands(self, operation):
69 """ exec operations with no operands """
70 try:
71 operation()
72 except BaseException as error:
73 print(error)
```

Wow, this code rocks now! :)

Even if…

Let’s pretend that we have to add the factorial function, could we just modify the catalog?

Unfortunately no.

There’s another place we have to modify… we have to modify also the compute function because we need to specify that the factorial function is a “one operand function”.

That’s bad, we do know that it is a one operand function, it’s obvious since we need to call the math.factorial(x) function passing just the x argument. If only there were a way to determine how many arguments a function needs at runtime…

There is actually. In the “inspect” module, there’s a “signature” function that can help us inspect the signature of our method at runtime. So, let’s start the REPL and do a quick test:

```
1>>> a = lambda x, y: x + y
2>>> from inspect import signature
3>>> my_signature = signature(a)
4>>> print(my_signature)
5(x, y)
6>>> print (my_signature.parameters)
7OrderedDict([(‘x', <Parameter "x">), (‘y', <Parameter "y">)])
8>>> print (len(my_signature.parameters))
92
```

Yes, amazing. We could determine at runtime how many operands our function needs!

```
1"""
2Engine class of the RPN Calculator
3"""
4
5import math
6from inspect import signature
7
8class rpn_engine:
9 def __init__(self):
10 """ Constructor """
11 self.stack = []
12 self.catalog = self.get_functions_catalog()
13
14 def get_functions_catalog(self):
15 """ Returns the catalog of all the functions supported by the calculator """
16 return {"+": lambda x, y: x + y,
17 "-": lambda x, y: x - y,
18 "*": lambda x, y: x * y,
19 "/": lambda x, y: x / y,
20 "^2": lambda x: x * x,
21 "SQRT": lambda x: math.sqrt(x),
22 "C": lambda: self.stack.pop(),
23 "AC": lambda: self.stack.clear()}
24
25 def push(self, number):
26 """ push a value to the internal stack """
27 self.stack.append(number)
28
29 def pop(self):
30 """ pop a value from the stack """
31 try:
32 return self.stack.pop()
33 except IndexError:
34 pass # do not notify any error if the stack is empty...
35
36 def compute(self, operation):
37 """ compute an operation """
38
39 function_requested = self.catalog[operation]
40 number_of_operands = 0
41 function_signature = signature(function_requested)
42 number_of_operands = len(function_signature.parameters)
43
44 if number_of_operands == 2:
45 self.compute_operation_with_two_operands(self.catalog[operation])
46
47 if number_of_operands == 1:
48 self.compute_operation_with_one_operand(self.catalog[operation])
49
50 if number_of_operands == 0:
51 self.compute_operation_with_no_operands(self.catalog[operation])
52
53 def compute_operation_with_two_operands(self, operation):
54 """ exec operations with two operands """
55 try:
56 if len(self.stack) < 2:
57 raise BaseException("Not enough operands on the stack")
58
59 op2 = self.stack.pop()
60 op1 = self.stack.pop()
61 result = operation(op1, op2)
62 self.push(result)
63 except BaseException as error:
64 print(error)
65
66 def compute_operation_with_one_operand(self, operation):
67 """ exec operations with one operand """
68 try:
69 op1 = self.stack.pop()
70 result = operation(op1)
71 self.push(result)
72 except BaseException as error:
73 print(error)
74
75 def compute_operation_with_no_operands(self, operation):
76 """ exec operations with no operands """
77 try:
78 operation()
79 except BaseException as error:
80 print(error)
```

As someone said, “That’s one small step for man, one giant leap for mankind.” :)

Note that in this last code we have modified the zero operands functions in the catalog from

```
1"C": self.stack.pop,
2"AC": self.stack.clear
```

to

```
1"C": lambda: self.stack.pop(),
2"AC": lambda: self.stack.clear()}
```

Why?

Well, the problem is that in the *compute *function we are trying to determine the number of parameters from the signature of the method. The problem is that for built-in methods written in C, we can’t do that.

Let’s try it by yourself, start a REPL:

```
1>>> from inpect import signature
2>>> a = []
3>>> my_sig = signature(a.clear)
4Traceback (most recent call last):
5 File "<stdin>", line 1, in <module>
6 File "C:UsersMASTROMATTEOAppDataLocalContinuumanaconda3libinspect.py", line 3033, in signature
7 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
8 File "C:UsersMASTROMATTEOAppDataLocalContinuumanaconda3libinspect.py", line 2783, in from_callable
9 follow_wrapper_chains=follow_wrapped)
10 File "C:UsersMASTROMATTEOAppDataLocalContinuumanaconda3libinspect.py", line 2262, in _signature_from_callable
11 skip_bound_arg=skip_bound_arg)
12 File "C:UsersMASTROMATTEOAppDataLocalContinuumanaconda3libinspect.py", line 2087, in _signature_from_builtin
13 raise ValueError("no signature found for builtin {!r}".format(func))
14ValueError: no signature found for builtin <built-in method clear of list object at 0x000001ED6EB18F88>
```

as you can see we can’t get the signature of a built-in method.

Our possibilities to solve this problem were:

- Handle this special case in our code, trapping the exception raised when we tried to get the signature for the self.stack.pop() function and the self.stack.clear() function
- Encapsulate the built-in functions in void lambdas, so as to have the signature functions extract the signature from our void lambda function and not from the built-in function contained.

And we have obviously chosen the second possibility since it is the most “Pythonic” we had. :)

That’s all folks. Today’s article has explored some aspect of functions and lambdas in Python and I hope you got the message I wanted to send.

think twice, code once.

Sometimes developers are lazy and don’t think too much at what can mean maintain bad code.

Let’s have a look at the first Peter’s code of the article and try to figure out what could have meant to add the factorial function then. We should have created another function, duplicated more code, and modified the “compute” function, right? With our last code we just need to add a single line to our catalog:

```
1"!": lambda x: math.factorial(x),
```

Try to think at what could have meant to add another feature to the program for logging all the calculations requested and the given results. We had been supposed to modify a dozen functions of our code to add the feature right? And we would have had to modify as well all the new functions that we will have inserted from now on. Now we can add the feature just in the three methods that really compute the requested calculation depending on the number of the operands requested.

Wait, three methods? Wouldn’t it be possible to have just a method that works regardless of the number of operands that are requested by the function? :)

Happy coding!

D.