E731 do not assign a lambda expression, use a def

I get this pep8 warning whenever I use lambda expressions. Are lambda expressions not recommended? If not why?

The recommendation in PEP-8 you are running into is:

Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name.


>     def f(x): return 2*x 


>     f = lambda x: 2*x 

The first form means that the name of the resulting function object is specifically 'f' instead of the generic ''. 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)

Assigning lambdas to names basically just duplicates the functionality of def - and in general, it's best to do something a single way to avoid confusion and increase clarity.

The legitimate use case for lambda is where you want to use a function without assigning it, e.g:

    sorted(players, key=lambda player: player.rank)

For simple operations, the operator module provides some useful options in attrgetter, itemgetter and methodcaller which can often replace labmdas that are just accessing attribute(s), item(s) and calling methods.

For example, the above could be done with operator.attrgetter like so:

    sorted(players, key=operator.attrgetter('rank'))

From: stackoverflow.com/q/25010167