为什么不能在 f 弦中使用 "await"?
Why isn't it possible to use "await" in f-strings?
为什么不能在 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
开始,不可能。根据 Python bug 跟踪器上 Issue 28942 -- await expressions in f-strings
上的消息,在 3.7
中是可能的。
至于原因,引入async
/await
表达式的PEP作者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
路线。
为什么不能在 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
开始,不可能。根据 Python bug 跟踪器上 Issue 28942 -- await expressions in f-strings
上的消息,在 3.7
中是可能的。
至于原因,引入async
/await
表达式的PEP作者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
路线。