In Python 3, is it possible to use short-circuit evaluation in an any call that doesn't have a for .. in expression in it?

102 Views Asked by At

In Python 3, is it possible to use short-circuit evaluation in an any call that doesn't have a for .. in expression in it?

I know that I can take advantage of short-circuit evaluation in a statement like this:

print('Hello' if True or 3/0 else 'World')  # this prints "Hello"

But if I try something similar with any, I get an exception because the 3/0 is evaluated:

print('Hello' if any([True, 3/0]) else 'World')  # this raises an exception

Is there a way I can use any to do this?

1

There are 1 best solutions below

0
dawg On

The issue here is not any, it is the immediate evaluation of 3/0 as the list literal is evaluated:

>>> [True, 3/0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

The only way to avoid that is to delay the evaluation until a later time with the use of a function or iterator:

def f(e):
    return e[0]/e[1] if isinstance(e,(list,tuple)) else e

>>> print('Hello' if any(map(f, [True, [3,0]])) else 'World')
Hello