Identifying Lambda expressions, An Alternative thought against PEP 8

I have been from Functional Programming background. Looking into aspects of teaching Clean Code on Python with Functional paradigm.

I could see PEP 8 recommends not to identify lambda expression. The one liner lambda identifiers helps to design better abstractions and design.

By recommending def for naming , we are providing developers to write large functions, which might do good for the starters But for larger programs , abstractions and design has better role to play.

Welcome @muthuishere .

The following reasons make me like the advice in PEP 8:

The reason given to not like it is sound

I defined f and cubed as follows

>>> f = lambda x: x * x * x
>>> def cubed(x):
...     """ Return the cube of x (x^3)"""
...     return x * x * x
>>> f(2)
>>> cubed(2)

So far, so good. Now when I have an error I seee the following:

>>> f("a")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: can't multiply sequence by non-int of type 'str'
>>> cubed("a")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in cubed
TypeError: can't multiply sequence by non-int of type 'str'

The PEP 8 supported version gives more and better information. It tells you where the “accident” happened, whereas the lambda only tells it failed in a lambda.

The rule does not forbid lambda, just a specific use

Lambda is not forbidden by PEP 8, just a specific use. It is the way I used it to define f that is targeted. Something like this is good:

calc_content = calc(side_length, lambda x: x * x * x)

So no, this is not a jab against, lambda, but an advice not to use it in a specific way.

The language should not be held responsible for style

PEP 8 is a style guide. Programming style is not a responsibility of the language designer, the core developers have judged it better to not have this use in their code, i.e. the Standard Library. The use of one way of using a language construct is discouraged.

In my own code I follow this. My code contains methods and functions that consist of the definition line (def), a docstring and 1, 2 or 3 lines of code. That is a deliberate choice, because separation of concerns and DRY (Don’t Repeat Yourself) mandates that for these cases. However, if a long calculation is required, I write that as a long flow of code. Such choices are the responsibility of the programmer, and unrelated to skill levels.

If you and your colleagues decide this is no good, mark it as where you do not want to follow PEP 8.

And another situation you want to evade

For the definition above we can request help, for the lambda this results in:

Help on function <lambda> in module __main__:

<lambda> lambda x

Not very helpful. For cubed:

Help on function cubed in module __main__:

    Return the cube of x (x^3)

A lot better.

1 Like