Search code examples
pythonevaluationshort-circuiting

Does Python's `all` function use short circuit evaluation?


I wish to use the Python all() function to help me compute something, but this something could take substantially longer if the all() does not evaluate as soon as it hits a False. I'm thinking it probably is short-circuit evaluated, but I just wanted to make sure. Also, is there a way to tell in Python how the function gets evaluated?


Editor's note: Because any and all are functions, their arguments must be evaluated before they are called. That often creates the impression of no short-circuiting - but they do still short-circuit.

To make sure that the short-circuiting can be effective, pass a generator expression, or other lazily evaluated expression, rather than a sequence. See Lazy function evaluation in any() / all() for details. Similarly, to force evaluation up-front, build a list or tuple explicitly; see How to prevent short-circuit evaluation? .


Solution

  • Yes, it short-circuits:

    >>> def test():
    ...     yield True
    ...     print('one')
    ...     yield False
    ...     print('two')
    ...     yield True
    ...     print('three')
    ...
    >>> all(test())
    one
    False
    

    From the docs:

    Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

    def all(iterable):
        for element in iterable:
            if not element:
                return False
        return True
    

    So when it returns False, then the function immediately breaks.