Using Operators as Functions to Avoid Lambdas
Let's give a basic example to illustrate this topic: "The reduce function"
reduce is a useful Python function that takes a callable and a sequence and returns the result of applying it to each sequential pair of values from the sequence, one of the most basic examples is to add all of the values from a list:
>>> from functools import reduce >>> numbers = [1, 2, 3, 4, 5] >>> reduce(lambda x, y: x + y, numbers) 15
Pretty straightforward, isn't it?
However, there's something I don't like that much about this code snippet: the use of the lambda expression.
There are many reasons why I try to reduce the use of lambda expressions as possible from my code, however, if you want to have a stronger opinion than mine about why you should avoid them as possible, take a look at this article from Trey Hunner on the topic.
Anyway, I have a better way to implement this piece of code and similars: Python's operator module
The Operator Module
As stated in the docs, the operator module "exports a set of efficient functions corresponding to the intrinsic operators of Python", this means that they implemented most of the operators from Python as efficient functions (Crafted in C language) , for example, Addition (+) and Substraction (-).
But the operator module is much more than arithmetic operators, there are functions for boolean operators, string operators, etc. I trust you on taking a deeper look at the docs to know more ;) (Specifically, this table)
Let's get rid of that ugly lambda expression in the previous example:
>>> import operator >>> from functools import reduce >>> numbers = [1, 2, 3, 4, 5] >>> reduce(operator.add, numbers)
As simple as it may seem, I've found some many cases in which using operator module has helped me to avoid some gnarly lambdas, for example, dynamic operations over unknown sets of data.
So, from now on, any time you feel tempted to use a lambda for this kind of things, try to think if the operator module has a handy function to do that for you.