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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With