Python's any
and all
built-in functions are supposed to short-circuit, like the logical operators or
and and
do.
However, suppose we have a function definition like so:
def func(s):
print(s)
return True
and use it to build a list of values passed to any
or all
:
>>> any([func('s'), func('t')])
's'
't'
True
Since the list must be constructed before any
is called, the function is also evaluated ahead of time, effectively preventing the short-circuiting.
If the function calls are expensive, evaluating all the functions up front is a big loss and is a waste of this ability of any
.
Knowing that any
accepts any kind of iterable, how can we defer the evaluation of func
, so that the short-circuiting of any
prevents the call of func(t)
?
map()
:any(map(func, ('s', 't')))
. Most people seem to have the opposite problem in Python3 — they want list outputs and python gives them generators and maps! – Darlingany
. The evaluations happen while constructing the list. – Vara