Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short circuit all() statement in Python

Tags:

python

Is there a way to short circuit an all() statement in Python?

So something like this:

return all([x != 0, 10 / x == 2, True, False, 7])

won't return an error if x is 0?

like image 431
Kevin Burke Avatar asked May 11 '26 19:05

Kevin Burke


1 Answers

That doesn't work because the list (that is, all its items) is evaluated before all is even called. You best option in this particular case is something like this:

return x != 0 and 10 / x == 2 and True and False and 7

I assume you already know this, so I'll provide you with another, more general solution that can also be applied if the list items are not hardcoded:

return all(f() for f in [lambda: x != 0, lambda: 10 / x == 2, 
                         lambda: True, lambda: False, lambda: 7])

That way the expressions will only be evaluated within the short-circuit all.

like image 164
Niklas B. Avatar answered May 14 '26 08:05

Niklas B.