If you want to await you need to be in an async def function. I propose changing Python to allow await, async for and async with in any function.
def myfunc():
await myasyncfunc() # same as if you're in an async function
await myfuture # inside a Task the future is awaited; outside, an Exception is raised
async for myasyncgenerator:
# same as if you're in an async function
...
async with with_item:
# same as if you're in an async function
...
Why this is helpful: if you use async you cannot make good use of async within Pythonâs constructs like @property, __getattr__() etc, C-implemented functions like len() and setattr(), and operator overrides like __lshift__() as you have to wait for for the async result before returning, which negates most of the point of async, to be able to do other, useful work while waiting. Also, any library which wants to support async and non-async has to be written twice - once async and once without. These together have made async only useful in niche cases, in particular not for web sites, the highlighted use case async was added for.
(aside: I tried using async in a Django website, and concluded it was unusable in its current form, which is why I decided to try and improve Python).
Iâve taken the trouble to create a proof-of-concept cpython which does this: GitHub - JonathanRoach/cpython-await-anywhere: The Python programming language, with await allowed anywhere ¡ GitHub (await-anywhere branch). Iâve tested this (make test without any fails) on Mac and Linux, debug, non-debug and optimised, but not Windows yet. Any feedback is very welcome (even âit doesnât workâ). The only new assumptions (over cpython) are that C standard setjmp() and longjmp() are available.
I am seeking a sponsor for a pep for this (@python/pep-editors please could you help me find one).
There is plenty more detail (eg âhow?â and âwhat are the catches?â), but lets get the communityâs views first, over to youâŚ