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