Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a pythonic one line statement like "return True if flag"?

Tags:

python

syntax

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.

like image 519
zell Avatar asked Jul 30 '26 17:07

zell


2 Answers

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.

like image 135
Xymostech Avatar answered Aug 01 '26 06:08

Xymostech


You could use:

return bool(flag) or None
like image 26
unutbu Avatar answered Aug 01 '26 07:08

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!