Why isn't it possible to use “await” in f-strings?

旧城冷巷雨未停 提交于 2019-12-08 14:54:20

问题


Why isn't it possible to use "await" in f-strings? Is there any way to coerce f-strings into evaluating the format expressions in the context of a coroutine function?

$ 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:


As of Python 3.6, this is not possible. It will be possible in 3.7 according to the messages on Issue 28942 -- await expressions in f-strings on the Python bug tracker.

As for the reason, the author of the PEP that introduced async/await expressions, Yury Selivanov, had this to say:

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.

and indeed, the tokenizer does seem to treat these specially.

You were right to be puzzled by this as formatted strings are documented as supporting all valid Python expressions (with the appropriate limitations those expressions entail i.e await in an async def function).

I don't believe there's any way to circumvent this at the moment. You'll need to stick with the .format route until the issue is resolved.



来源:https://stackoverflow.com/questions/43120796/why-isnt-it-possible-to-use-await-in-f-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!