16

为什么不能在 f-strings 中使用“await”?有没有办法强制 f 字符串在协程函数的上下文中评估格式表达式?

$ python3 
Python 3.6.0 (default, Mar  4 2017, 12:32:37) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> async def a(): return 1
... 
>>> async def b(): return 'The return value of await a() is {}.'.format(await a())
... 
>>> async def c(): return f'The return value of await a() is {await a()}'
... 
  File "<fstring>", line 1
    (await a())
           ^
SyntaxError: invalid syntax
4

1 回答 1

14

在 Python3.6中,这是不可能的3.7根据问题 28942f-strings上的消息,这将是可能的——在 Python 错误跟踪器上等待表达式。

至于原因,介绍/表达式的PEP的作者Yury Selivanov 是这样说的:asyncawait

我怀疑原因是async/await在 3.5/3.6 中不是正确的关键字,并且我们在标记器中识别它们的技巧在 f-strings 中不起作用。

async一旦我们制作/await关键字,我将把这个问题分配给我自己,以确保它在 3.7 中得到解决。

事实上,tokenizer 似乎确实特别对待这些

您对此感到困惑是对的,因为格式化的字符串被记录为支持所有有效的 Python 表达式(这些表达式具有适当的限制,即awaitasync def函数中)。

我不相信目前有任何方法可以规避这一点。.format在问题解决之前,您需要坚持路线。

于 2017-03-30T14:37:30.180 回答