python-3.x asyncio,信号量不能与async with as语法一起使用

mo49yndu  于 2023-04-13  发布在  Python
关注(0)|答案(1)|浏览(115)

我是一个Python编程爱好者,最近在学习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
"""

我很好奇为什么会发生这种情况。是因为信号量对象不能与async with as语法一起使用吗?
我使用的Python版本是在AlmaLinux上运行的Python 3.9,我已经在Python中查找了'as'关键字的语法要求,并尝试在Stack Overflow上搜索答案,但我无法找到为什么会发生这种情况。如果有人能帮助我澄清这个困惑,我将不胜感激,欢迎任何回复。谢谢。

h79rfbju

h79rfbju1#

请考虑以下示例:

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())

图纸:

<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]>

您会看到None,因为从__aenter__返回的值是None
来源:https://github.com/python/cpython/blob/main/Lib/asyncio/locks.py#L12

相关问题