【问题标题】:Why isn't it possible to use "await" in f-strings?为什么不能在 f-strings 中使用“await”?
【发布时间】:2017-08-24 13:14:27
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    确实,tokenizer 似乎确实是 treat these specially

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

    我认为目前没有任何方法可以规避这种情况。在问题解决之前,您需要坚持使用 .format 路由。

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2023-02-10
      • 1970-01-01
      • 2020-03-05
      • 2019-10-28
      相关资源
      最近更新 更多