I could not find anything on this in PEP 8. Did I miss anything?
( Not that I disagree: PEP 8’s silence can easily be taken for tacit permission. )
Too bad that popular tooling (by default) does not support the single line def
style. E.g.
- Black inserts 2–3 newlines, depending on context;
- Pylint complains
C0321 (multiple-statements): More than one statement on a single line
.
I regularly see argumentation about code along these lines, but I am skeptical of it. (But see caveat below.)
It does not at all agree with my own experience: if anything, I recognize the =
and the lambda …: …
forms first, then register the identifier to the left soon after, and finally the body (if I choose to look at it). I do not even have to actively read for this: the ‘form’ of the text is instantly recognizable, and of course there is also syntax highlighting. I do have to read to register the identifier, and more actively so to understand the body.
Same for def
: I first recognize the def … ( … ): …
form (as a whole), then the name, then the arguments + body (if I choose to).
People do not tend to read letter for letter, or even strictly left-to-right. Programmers when reading code (somewhat famously) even less so. It seems really unlikely to me that large numbers or programmers would be having noticeable trouble reading code on such as small scale. ( Only 4–5 non-cramped tokens! That’s like almost subitizing scale. )
( See also: Eye movement in reading - Wikipedia, Word recognition - Wikipedia )
Caveat: I fully grant that unfamiliar code is harder to read. If you have never seen the name = lambda args: body
form, then of course there will be a hiccup. The situation is the same for unfamiliar words/phrases in natural languages. Assigned lambdas are uncommon in Python, so they are more likely to be unfamiliar – even if only for a short while.
Previously I stated
But this is false: it offers two arguments. The second one is irrelevant (as it only argues that using a lambda is no better than using def
), but the first one is valid:
The [def f(…): …
] 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.