What is the difference between "async with lock" and "with await lock"?

Viewed 961

I have seen two ways of acquiring the asyncio Lock:

async def main(lock):
  async with lock:
    async.sleep(100)

and

async def main(lock):
  with await lock:
    async.sleep(100)

What is the difference between them?

3 Answers

there should be no functional difference

BUT the latter was removed from python 3.9 see at the bottom of the page https://docs.python.org/3/library/asyncio-sync.html

Changed in version 3.9: Acquiring a lock using await lock or yield from lock and/or with statement (with await lock, with (yield from lock)) was removed. Use async with lock instead.

async with lock is an statement for asynchronous context manager which suspends execution in enter (__aenter__ ) and exit (__aexit__) methods. async with is supported from Python 3.5 and is fully described in PEP 492. with await lock is the same but in Python 3.9 is officially removed and it is recommended to use async with lock instead.

Related