Skip to content

Commit a86e914

Browse files
committed
Create lambda_may_not_be_necessary.rst.
1 parent 2e422f6 commit a86e914

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
Lambda may not be necessary
2+
===========================
3+
4+
Summary
5+
-------
6+
7+
The body of a lambda expression is just a function call on the same argument list as the lambda itself. The lambda is probably unnecessary. Improve code readability by removing the lambda and calling the function directly on the argument list.
8+
9+
Description
10+
-----------
11+
12+
Lambda expressions enable you to create inline, anonymous functions. A lambda serves no purpose when it is just a call to a named function. It only makes the code harder to read.
13+
14+
Examples
15+
----------
16+
17+
Lambda is just a function call
18+
..............................
19+
20+
The lambda expression below does nothing other than call the function ``multiply_by_two()``. In this situation the lambda is pointless and only makes the code harder to read.
21+
22+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
23+
24+
.. code:: python
25+
26+
def multiply_by_two(n):
27+
return n * 2
28+
29+
anonymous_function = lambda x: multiply_by_two(x) # unnecessary lambda
30+
31+
anonymous_function(5)
32+
33+
Solutions
34+
---------
35+
36+
Remove the lambda and call the function directly
37+
................................................
38+
39+
The modified module below has removed the unnecessary lambda and just calls the ``multiply_by_two()`` function directly. This code is more direct and more concise than the original code that used a lambda.
40+
41+
.. code:: python
42+
43+
def multiply_by_two(n):
44+
return n * 2
45+
46+
multiply_by_two(5)
47+
48+
References
49+
----------
50+
- `Oliver Fromme <http://www.secnetix.de/olli/Python/lambda_functions.hawk>`_

0 commit comments

Comments
 (0)