Using assignment expressions inside f-strings

Hi there!

It would be a handy f-string feature if you could use Assignment Expressions inside them as follows.

from math import sqrt

number = 25
print(f"result is {result:=sqrt(number)}")

if result%2 == 0:

Now, it’s doable like:

from math import sqrt

number = 25
result = sqrt(number)

print(f"result is {result}")

if result%2 == 0:

This is just a feature that came into my mind when I was working on a case and thought that this feature may make my code cleaner!


You can already do

print(f"result is {(result:=sqrt(number))}")

Thank you Jean!
I almost forgot this! I missed those parentheses.

What do the parentheses do? Where can one read about this? And also… isn’t there one missing?

The parentheses group an expression. They don’t “do” anything, except that a colon is a separator. It’s like the difference between:

print(1, 2) # two arguments to the function call
print((1, 2)) # one argument (a tuple)

Commas have special meaning in parameter lists, so parentheses can be used to prevent that meaning and force the comma to mean “make a tuple”. Colons have special meaning in f-strings, so similarly, you can’t use them in the expression without parentheses:

>>> f"{lambda: 1}"
  File "<stdin>", line 1
SyntaxError: f-string: invalid syntax
>>> f"{(lambda: 1)}"
'<function <lambda> at 0x7fc6d93d7d80>'
>>> f"{1:2}"
' 1'
>>> f"{{1:2}}"
>>> f"{({1:2})}"
'{1: 2}'

In the last set, 1:2 means “format the value 1 using the style 2” (where 2 simply defines a width - that’s why there’s a leading space), but {1:2} is a dictionary display (sometimes called a dict literal), and so we see the dictionary. Except that we don’t see that in the second case (a dict’s repr would have a space in it, see the third example); this is another place where the parentheses force a different interpretation, this time preventing the double open brace from meaning “put an actual open brace here”.

So, while the parens don’t do anything in particular, they can be used to indicate your intention and prevent something else from happening.


The parentheses are here only to prevent the colon : of the walrus operator := to be interpreted as introducing the format specifier. So it’s just a normal assignment operation then. Got it. I thought there was some additional magic at play here. Thanks.

1 Like