I have a specific situation in which I would like to do the following (actually it is more involved than this, but I reduced the problem to the essence):
>>> (lambda e: 1)(0) if (lambda e: True)(0) else (lambda e: 2)(0)
True
which is a difficult way of writing:
>>> 1 if True else 2
1
but in reality '1','True' and '2' are additional expressions that get evaluated and which require the variable 'e', which I set to '0' for this simplified code example.
Note the difference in output from both expressions above, although
>>> (lambda e: 1)(0)
1
>>> (lambda e: True)(0)
True
>>> (lambda e: 2)(0)
2
The funny thing is that this is a special case, because if I replace '1' by '3' I get the expected/desired result:
>>> (lambda e: 3)(0) if (lambda e: True)(0) else (lambda e: 2)(0)
3
It's even correct if I replace '1' by '0' (which could also be a special case since 1==True and 0==False)
>>> (lambda e: 0)(0) if (lambda e: True)(0) else (lambda e: 2)(0)
0
Also, if I replace 'True' by 'not False' or 'not not True', it still works:
>>> (lambda e: 1)(0) if (lambda e: not False)(0) else (lambda e: 2)(0)
1
>>> (lambda e: 1)(0) if (lambda e: not not True)(0) else (lambda e: 2)(0)
1
Another alternative formulation uses the usual if..then..else statement and does not produce the error:
>>> if (lambda e: True)(0):
(lambda e: 1)(0)
else:
(lambda e: 2)(0)
1
What explains this behavior? How can I solve this behavior in a nice way (avoid to use 'not not True' or something?
Thanks!
PS: the question revealed a bug in Python, see https://bugs.python.org/issue25843 for the issue tracking.
(lambda e: 1)
is just a function that always returns1
when called.(lambda e: 3)
returns3
. I don't see any oddities or special cases. Can you clarify what the problem is? I know this is a toy example, but there is no reason to do a lambda like this... the lambda is just an expression that can be added directly to theif
.(lambda e: 1)(0)
instead of1
, because the output is not known in general. I hope this makes it clearer...(lambda e: 1)(0)
and not(lambda e: 1)
.(lambda e: 1)(0) if (lambda e: False)(0) else (lambda e: 1)(0)
(meaning the else clause runs) returns1
, notTrue
.