Reputation: 99418
From Python in a Nutshell, why is it that
An
async def
coroutine function cannot contain anyyield
.
Thanks.
Upvotes: 1
Views: 72
Reputation: 160407
This is stated in the rationale of PEP 492 which introduced async
/await
and forbid the use of yield
inside them:
Current Python supports implementing coroutines via generators (PEP 342), further enhanced by the yield from syntax introduced in PEP 380. This approach has a number of shortcomings:
- It is easy to confuse coroutines with regular generators, since they share the same syntax; this is especially true for new developers.
- Whether or not a function is a coroutine is determined by a presence of yield or yield from statements in its body, which can lead to unobvious errors when such statements appear in or disappear from function body during refactoring.
- Support for asynchronous calls is limited to expressions where yield is allowed syntactically, limiting the usefulness of syntactic features, such as with and for statements.
This only applies in Python 3.5
In Python 3.6, PEP 525 came along and lifted the ban with asynchronous generators. Now using yield
inside async def functions results in an asynchronous generator being created.
Upvotes: 4