Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 609
lyschoening Avatar asked Mar 30 '17 14:03

lyschoening


People also ask

Are F strings better than concatenation?

From a readability standpoint, f-string literals are more aesthetically pleasing and easier to read than string concatenation.

When should I use await Python?

You must use the await keyword if and only if the function you are calling is a coroutine.

What is await in Python?

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.


1 Answers

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.

like image 150
Dimitris Fasarakis Hilliard Avatar answered Oct 18 '22 00:10

Dimitris Fasarakis Hilliard