Issue
I am a Python programming enthusiast, and recently encountered the issue demonstrated in the code below while learning about the usage of asyncio.
import asyncio
async def a():
sem = asyncio.Semaphore(2)
async with sem:
print(sem)
async def b():
async with asyncio.Semaphore(2) as sem:
print(sem)
if __name__ == "__main__":
asyncio.run(a())
asyncio.run(b())
"""
output:
<asyncio.locks.Semaphore object at 0x7f28e4eaca60 [unlocked, value:1]>
None
"""
I am curious as to why this is happening. Is it because asyncio.Semaphore objects cannot be used with the async with as syntax?
The Python version I am using is Python 3.9 running on AlmaLinux, I have looked up the syntax requirements for the 'as' keyword in Python and tried searching for answers on Stack Overflow, but I haven't been able to find out why this is happening. I would appreciate it if someone could help me clear up this confusion, and any reply are welcome. Thanks.
Solution
Consider this example:
import asyncio
async def a():
sem = asyncio.Semaphore(2)
async with sem:
print(sem)
async def b():
async with (actual_semaphore:=asyncio.Semaphore(2)) as value_returned_from_aenter:
print(f'{value_returned_from_aenter=}')
print(f'{actual_semaphore=}')
if __name__ == "__main__":
asyncio.run(a())
asyncio.run(b())
Prints:
<asyncio.locks.Semaphore object at 0x7f41067e69e0 [unlocked, value:1]>
value_returned_from_aenter=None
actual_semaphore=<asyncio.locks.Semaphore object at 0x7f41067e69e0 [unlocked, value:1]>
You see None
because the vale returned from __aenter__
is None
.
Source: https://github.com/python/cpython/blob/main/Lib/asyncio/locks.py#L12
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.