Python: lambda vs if/else

Question:

I tried to replace lambda self.status: partial if max_refundable == amount else self.status = refunded with if/else to make it in one line. However, it doesn’t work as expected. Anyone knows where the problem is?

if max_refundable == amount:
    self.status = partial
else:
    self.status = refunded
Asked By: user9252255

||

Answers:

The syntax is as follows:

a = 1
b = 3
a = a+b if a == 2 else b

In your case, it would look like this:

self.status = partial if max_refundable == amount else refunded
Answered By: Reblochon Masque

Because that is invalid syntax

lambda self.status: partial if max_refundable == amount else self.status = refunded

is equivelent to

def _lambda_func_(self.status):
    return partial if max_refundable == amount else self.status = refunded

which isn’t what you want (self.status is not a valid argument name). You don’t need a function, just do

self.status = partial if max_refundable == amount else refunded
Answered By: FHTMitchell
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.