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

北城余情 提交于 2019-11-27 01:31:38

The behaviour is guaranteed. I've contributed a patch, which was accepted and merged recently, so if you grab the latest sources you will see that the short-circuiting behaviour is now explicitly enforced.

git clone https://github.com/python/cpython.git
grep Short-circuit cpython/Lib/test/test_builtin.py

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.

This page is the only stack overflow page that comes up for me when searching "any all short circuit python"

So: in case you landed here looking for a simple "do any/all always always short-circuit?"

They do, but there is a gotcha: using a list comprehension can make it seem like you are overriding the short-circuiting behavior:

def hi():
    print('hi')
    return True

>>> any(hi() for num in [1, 2, 3, 4])
hi

>>> any([hi() for num in [1, 2, 3, 4]])
hi
hi
hi
hi

The list comprehension executes before any() does.

or as @russianfool suggests:

>>> any((hi(), hi(), hi(), hi()))
hi
hi
hi
hi

The complete tuple is evaluated before any kicks off.

(This is also true of the lists above: [1, 2, 3, 4] is completely evaluated both times above.)

Also worth noting:

any(hi(), hi(), hi(), hi())

throws TypeError: any() takes exactly one argument (4 given)

It HAS to short circuit, since it could be given an unbound iterable. If it did not short circuit then this would never terminate:

any(x == 10 for x in itertools.count())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!