Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python defined or operator

Is there some conditional operator in Python which would evaluate the first operand and return its value if it’s not None, or if it’s None, evaluate and return the second operand? I know that a or b can almost do this, except that it does not strictly distinguish None and False. Looking for something similar to // operator in Perl.

The goal is to write both a and b only once, therefore alternative a if a is not None else b doesn’t work either – both a and b can be expensive expressions.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

How about using the walrus operator?

tmp if (tmp := a()) is not None else b()

It will be faster than writing your own function, as function calls in Python incur a large overhead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading