为什么不能在f字符串中使用"await"?

lys*_*ing 14 python python-3.x python-3.6 f-string

为什么不能在f字符串中使用"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
Run Code Online (Sandbox Code Playgroud)

Jim*_*ard 12

从Python开始3.6,这是不可能的.3.7根据问题28942f-strings上的消息,可以在Python bug跟踪器上等待表达式.

至于原因,引入/ 表达的PEP的作者Yury Selivanov有这样的说法:asyncawait

我怀疑原因是async//await不是3.5/3.6中的正确关键字,而我们在tokenizer中识别它们的hack在f字符串中不起作用.

我会将此问题分配给自己,以确保在我们制作async/ await关键字后,它已在3.7中得到解决.

事实上,标记器确实似乎特别对待这些.

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

我不相信目前有任何办法可以绕过这一点..format在问题解决之前,您需要坚持使用路线.