为什么不能使用"await"?在f弦上? [英] Why isn't it possible to use "await" in f-strings?

查看:220
本文介绍了为什么不能使用"await"?在f弦上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能在f字符串中使用"await"?有什么办法可以在协程函数的上下文中强制f字符串评估格式表达式?

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

推荐答案

从Python 3.6开始,此是不可能的.根据问题28942上的消息,在3.7中将是可能的-等待f-strings 在Python错误跟踪器上.

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.

由于这个原因, PEP 的作者async/await表达式Yury Selivanov这样说:

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

我怀疑原因是async/await在 3.5/3.6,我们在分词器中发现的骇客无法在f字串中工作.

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.

我将把这个问题分配给我自己,以确保在3.7中已解决 一旦我们创建了async/await关键字.

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).

我不认为目前有任何方法可以规避这一点.您需要坚持使用.format路线,直到问题解决.

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.

这篇关于为什么不能使用"await"?在f弦上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆