The Python Oracle

Why "yield from" does not work as expected in all() or any()?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Luau

--

Chapters
00:00 Why &Quot;Yield From&Quot; Does Not Work As Expected In All() Or Any()?
01:21 Accepted Answer Score 2
01:55 Thank you

--

Full question
https://stackoverflow.com/questions/3373...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x

#avk47



ACCEPTED ANSWER

Score 2


func1 is a function returning a generator while func2 and func3 are regular functions:

>>> type(func1())
<class 'generator'>
>>> type(func2())
All 3 ok !
<class 'NoneType'>

That's because:

ok3 = all((yield from yield_random()) for i in range(3))

is actually equivalent to:

def _gen():
    for i in range(3):
        r = yield from yield_random()
        yield r
ok3 = all(_gen())

This code doesn't yield anything since the yield from statement is encapsulated in a generator. You can even run it outside of a function, in your console for instance:

>>> all((yield from yield_random()) for i in range(3))
False

Though it probably doesn't do what you expect:

>>> list((yield from yield_random()) for i in range(3))
['OK', True, False, False]