[Python-Dev] PEP 8: Discourage named lambdas? (original) (raw)

Raymond Hettinger python at rcn.com
Sun May 4 12:31:12 CEST 2008


[Terry Reedy]

Some people write somename = lambda args: expression instead of the more obvious (to most people) and, dare I say, standard def somename(args): return expression

Though def-statements are usually the best way to go, there are some reasonable cases where the first form reads better. I say leave it to the programmer to decide. Experience will quickly teach the def-statement is more flexible.

Another thought is that I often give the advice that if a long-line becomes hard to read, then an easy solution is to pull-out an inner expression and give it a name. This is especially true when the intended purpose of the inner expression isn't obvious and giving it a name adds clarity. I would have to burden this advice with an admonition to go further and move the relevant code farther away from where it is used:

for k,g in groupby(iterable, key=lambda r: (r[0].lower(), r[5].lower())): ...

lastname_firstname = lambda r: (r[0].lower(), r[5].lower()) for k, g in groupby(iterable, key=lastname_firstname): ...

That transformation adds clarity. Going further and creating a separate def-statement outside the current function would just move the relevant code farther away and impair readability.

Also, I'm somewhat opposed to using PEP 8 in this way. Somehow, the PEPs recommendations seem to get occasionally interpreted as law. IMO, the PEP should be limited to things that have a real impact on code being maintained by multiple programmers. It should not grow into a general purpose set of situation independent prejudgments about which constructs should be favored over others (i.e. programmer x hates for-else so those should be avoided in favor of using flags or programmer y thinks it's uncool to have a return-statement anywhere but the end of a function).

What do our style mavens think?

-1

Raymond



More information about the Python-Dev mailing list