Is the shortcircuit behaviour of Python's any/all explicit?

后端 未结 4 1562
面向向阳花
面向向阳花 2020-11-28 11:04

Prompted by the discussion here

The docs suggest some equivalent code for the behaviour of all and any

Should the behaviour of the equivalent code be conside

4条回答
  •  我在风中等你
    2020-11-28 11:42

    The docs say

    "Return True if any element of the iterable is true. If the iterable is empty, return False. EQUIVALENT TO:" (emphasis mine) ...

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

    If any didn't short circuit, it wouldn't be EQUIVALENT to the posted code since the posted code clearly short circuits. You could consume more of a generator than you want to for example. In light of that, I say that the short circuiting behavior is guaranteed.

    The exact same argument could be made for all.

提交回复
热议问题