Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Perl's idiom do this or that, usually known as "or die"?

IN Perl it's quite common to do things like function() || alternative(). If the first returns false it will run the second one.

How can this be easily implemented in Python?

Update

Examples (pseudocode):

x = func() or raise exeption
x = func() or print(x)
func() or print something

If possible solutions should work with Python 2.5+

Note: There is an implied assumption that you cannot modify the func() to raise exceptions, nor to write wrappers.

like image 469
sorin Avatar asked Sep 26 '11 09:09

sorin


2 Answers

Use or: Python uses short circuit evaluation for boolean expressions:

function() or alternative()

If function returs True, the final value of this expression is determined and alternative is not evaluated at all.

like image 106
rocksportrocker Avatar answered Nov 16 '22 05:11

rocksportrocker


you can use or:

function() or alternative()

also, there is conditional expression defined in PEP 308:

x = 5 if condition() else 0

Which is sometimes useful in expressions and bit more readable.

like image 2
Michał Šrajer Avatar answered Nov 16 '22 04:11

Michał Šrajer