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

时间:2017-03-30 14:30:00

标签: python python-3.x python-3.6 f-string

为什么不能在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

1 个答案:

答案 0 :(得分:10)

从Python 3.6开始,此不可能。根据Python错误跟踪器上的Issue 28942 -- await expressions in f-strings上的消息,可以在3.7中进行。

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

  

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

     

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

实际上,标记化器确实似乎treat these specially

由于格式化字符串被记录为支持all valid Python expressions(在await函数中这些表达式需要async def),因此您对此感到困惑。

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

相关问题