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

标签 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

最佳答案

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

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

I suspect the reason is that async/await aren't proper keywords in 3.5/3.6, and the hacks we have in tokenizer to recognize them aren't working in f-strings.

I'll assign this issue to myself to make sure it's resolved in 3.7 once we make async/await keywords.

事实上,分词器似乎确实 treat these specially .

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

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

关于python - 为什么不能在 f 字符串中使用 "await"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43120796/

相关文章:

python - 不可能创建具有特定游戏的环境(健身房复古)

python - 是否有可能知道 python 进程正在运行哪个脚本?

python - pandas value_counts( ) 不按降序排列

python - 无法解析 h4 标签内的数据 : Python3

python-3.x - pypy3 import psycopg2错误( undefined symbol :PyCoder_Encoder)

来自 python 的 redis 在 cli 中显示

python - 如何使用 .loc 设置为 pandas 中的其他列值

python - 我如何使列表成为列表的列表?

Python 3.5 全局变量不会追加

python - ZODB python 数据库与 Filestorage : why do temporary files stay on the disk?