【问题标题】:How to use Asynchronous Comprehensions?如何使用异步理解?
【发布时间】:2017-05-10 02:18:04
【问题描述】:

我正在尝试在 MacOS Sierra (10.12.2) 中使用 Python 3.6's async comprehensions,但我收到了 SyntaxError

这是我尝试过的代码:

print( [ i async for i in range(10) ] )
print( [ i async for i in range(10) if i < 4 ] )
[i async for i in range(10) if i % 2]

我收到async loops 的语法错误:

result = []
async for i in aiter():
if i % 2:
    result.append(i)

所有代码都是从 PEP 复制/粘贴的。

终端输出:

>>> print([i for i in range(10)])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print([i async for i in range(10)])            
  File "<stdin>", line 1
    print([i async for i in range(10)])
                  ^
SyntaxError: invalid syntax
>>> print([i async for i in range(10) if i < 4])
  File "<stdin>", line 1
    print([i async for i in range(10) if i < 4])
                 ^
SyntaxError: invalid syntax
>>> 

【问题讨论】:

    标签: python python-3.x asynchronous async-await python-3.6


    【解决方案1】:

    这符合预期。问题是这些形式的理解只允许 async def 函数中使用。在外部(即在您的 REPL 中输入的顶层),它们按照定义提出 SyntaxError

    这在 PEP 的规范部分中有说明,具体来说,for asynchronous comprehensions

    异步推导只允许在 async def 函数内

    同样,使用await in comprehensions

    这仅在async def 函数体中有效

    对于async loops,您既需要一个符合必要接口(定义__aiter__)的对象,又需要放置在async def 函数中。同样,这是在相应的 PEP 中指定的:

    将没有__aiter__ 方法的常规迭代传递给async forTypeError。在async def 函数之外使用async forSyntaxError

    【讨论】:

    • 有没有一种快速的方法可以从 REPL 调用 async def 函数并等待它完成?
    • @tbodt 我知道您在 6 个月前就问过了,但是对于其他想知道的人,您可以在 REPL 中使用 asyncio.get_event_loop().run_until_complete(some_async_function()) 来同步运行该函数。
    猜你喜欢
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2020-01-17
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多