Reputation: 11707
I'm checking this function which should either loop forward or backward in an array depending on the parameters passed to it. To update the index, the code has something like this:
>>> def updater(me, x, y):
... fun = lambda x : x + 1 if x < y else lambda x : x - 1
... return fun(me)
...
>>> updater(2, 1, 0)
<function <lambda> at 0x7ff772a627c0>
I realize that the above example can be easily corrected if I just use a simple if-return-else-return
sequence but this is just a simplification, and in the actual code it's more than just checking two integers. And yes, there is a one-liner conditional involved which returns a function (don't ask, not my own code).
Sanity-checking my interpreter...
>>> updater = lambda x: x + 1
>>> updater(2)
3
So why does the first example return an function?
Upvotes: 1
Views: 45
Reputation: 298392
These parentheses should help you see how your code is being interpreted:
fun = (lambda x : (x + 1 if x < y else (lambda x : x - 1)))
So to solve your problem, just add some more parentheses:
fun = (lambda x: x + 1) if x < y else (lambda x: x - 1)
Or use only one lambda:
fun = lambda x: x + (1 if x < y else -1)
Upvotes: 2