Is the Python equivalent of the Perl idiom doing this or that, commonly called "or dying"?

In Perl, you often have to do things like function() || alternative() function() || alternative() . If the first returns false, it will run the second.

How is this easy to implement in Python?

Update

Examples (pseudo-code):

 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 assumption that you cannot modify func () to throw exceptions or to write wrappers.

+6
source share
4 answers

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

 function() or alternative() 

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

+5
source

you can use or :

 function() or alternative() 

there is also a conditional expression defined in PEP 308 :

 x = 5 if condition() else 0 

This is sometimes useful in expressions and more readable.

+2
source
 function() or alternative() 

The mechanism is exactly the same.

+1
source

try with or :

 >>> def bye(): return 3 >>> print bye() or 342432 3 

Unfortunately, this does not work, as in Perl, because in Perl, after assigning the type my $c = $d || 45; my $c = $d || 45; you have a value of 45 in $c if $d is undefined. In Python, you get the error NameError: name 'd' is not defined

+1
source

Source: https://habr.com/ru/post/898048/


All Articles