Skip to content

Commit fe8ed14

Browse files
committed
Updated docs, link.
1 parent 449c4b4 commit fe8ed14

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
Assigning a `lambda` expression to a variable
2+
=============================================
3+
4+
The sole advantage that a ``lambda`` expression has over a ``def`` is that the ``lambda`` can be anonymously embedded within a larger expression. If you are going to assign a name to a ``lambda``, you are better off just defining it as a ``def``.
5+
6+
From the PEP 8 Style Guide:
7+
8+
Yes:
9+
10+
def f(x): return 2*x
11+
12+
No:
13+
14+
f = lambda x: 2*x
15+
16+
The first form means that the name of the resulting function object is specifically 'f' instead of the generic '<lambda>'. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)
17+
18+
Examples
19+
----------
20+
21+
The following code assigns a ``lambda`` function which returns the double of its input to a variable. This is functionally identical to creating a ``def``.
22+
23+
.. code:: python
24+
25+
f = lambda x: 2 * x
26+
27+
Solutions
28+
---------
29+
30+
Use a ``def`` for named expressions
31+
...................................
32+
33+
Refactor the ``lambda`` expression into a named ``def`` expression.
34+
35+
.. code:: python
36+
37+
def f(x): return 2 * x
38+
39+
References
40+
----------
41+
42+
- `PEP 8 Style Guide - Programming Recommendations <http://legacy.python.org/dev/peps/pep-0008/#programming-recommendations>`_
43+
- `Stack Overflow - Do not assign a lambda expression <http://stackoverflow.com/questions/25010167/e731-do-not-assign-a-lambda-expression-use-a-def>`_
44+
- pep8 - E731

docs/index.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ The Little Book of Python Anti-Patterns
1818
|
1919
2020

21-
:github_badge:`quantifiedcode/python-code-patterns`
21+
:github_badge:`quantifiedcode/python-anti-patterns`
2222

2323
Welcome, fellow Pythoneer! This is a small book of Python **anti-patterns** and **worst practices**.
2424

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy