def even(x): return x % 2 == 0 def even(x): return x % 2 == 0 formulas = {
'sum': lambda x,y: x+y,
'subst': lambda x,y: x-y,
'mult': lambda x,y: x*y,
'pow': lambda x,y: x**y
}
def apply_operator(operation_name, x, y):
operation=formulas[operation_name]
return operation(x,y)
Using "def"s there would kill readability and easiness of coding.Most simple uses of lambda like this can be substituted with functions from the operator module:
import operator
formulas = {
'sum': operator.add,
'subst': operator.sub,
'mult': operator.mul,
'pow': operator.pow
}However, what I meant was that for fast, quick coding, if your 'operator' function is really simple, then lambda fints perfectlu.
I know the Zen of Python says: "There should be one—and preferably only one—obvious way to do it", but i don't align to that principle. I think there should be more than one way to do something, and one should choose one that fits the best.
I'm happy for you to use lambdas in an expression context, if that's how you like to roll, but assignment is a statement anyway, so it doesn't matter there and you might as well choose the one that produces helpful tracebacks.
def even(x): return not(x % 2)I suspect that it will be easier for core Python developers rather that general Python programmers because they will be more intimately familiar with the conversion rules. I would be more comfortable with such a construct in C or C++, because I am more confident in those conversion rules. But, even though Python's are quite similar, I had to check myself before making my comment, because I knew they were similar, but I was not sure what they were. The situation in the stackoverflow comment is also not quite the same: asking a question about the relationship of numbers (is x modded by 2 equal to zero) is a special case of using integers in a boolean context. Saying it's Pythonic to use an integer in a boolean context does not necessarily mean it's best to always do so.
I don't feel that there is anything incidental about that. Integer zero is logically false and any other integer is logically true.
That said I don't add unneeded parentheses for simple expressions or sub-expressions consisting only of exponents, multiplications, divisions, additions and/or subtractions.