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
From a readability standpoint, f-string literals are more aesthetically pleasing and easier to read than string concatenation.
You must use the await keyword if and only if the function you are calling is a coroutine.
The keyword await passes function control back to the event loop. (It suspends the execution of the surrounding coroutine.) If Python encounters an await f() expression in the scope of g() , this is how await tells the event loop, “Suspend execution of g() until whatever I'm waiting on—the result of f() —is returned.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With