Reputation: 10204
Is there a way to write a one line python statement for
if flag:
return True
Note that this can be semantically different from
return flag
In my case, None is expected to be returned otherwise.
I have tried with "return True if flag", which has syntactic error detected by my emacs.
Upvotes: 2
Views: 571
Reputation: 180441
You could use bool return bool(flag)
if you return False when the flag is a falsey value.
Or maybe the following depending on whether you return None:
return True if flag else None
If you are testing the return value if False
and if True
will both evaluate to False so unless you are explicitly testing for None then return bool(flag)
is sufficient.
Upvotes: 0
Reputation: 9850
return True if flag
doesn't work because you need to supply an explicit else
. You could use:
return True if flag else None
to replicate the behaviour of your original if statement.
Upvotes: 8