What does = (equal) do in f-strings inside the expression curly brackets?

This was introduced in python 3.8. It helps reduce a lot of f'expr = {expr} while writing codes. You can check the docs at What's new in Python 3.8.

A nice example was shown by Raymond Hettinger in his tweet:

>>> from math import radians, sin
>>> for angle in range(360):
        print(f'{angle=}\N{degree sign} {(theta:=radians(angle))=:.3f}')
angle=0° (theta:=radians(angle))=0.000
angle=1° (theta:=radians(angle))=0.017
angle=2° (theta:=radians(angle))=0.035
angle=3° (theta:=radians(angle))=0.052
angle=4° (theta:=radians(angle))=0.070
angle=5° (theta:=radians(angle))=0.087
angle=6° (theta:=radians(angle))=0.105
angle=7° (theta:=radians(angle))=0.122
angle=8° (theta:=radians(angle))=0.140
angle=9° (theta:=radians(angle))=0.157
angle=10° (theta:=radians(angle))=0.175
...

You can also check out this to get the underlying idea on why this was proposed in the first place.


As mention here:

Equals signs are now allowed inside f-strings starting with Python 3.8. This lets you quickly evaluate an expression while outputting the expression that was evaluated. It's very handy for debugging.:

It mean it will run the execution of the code in the f-string braces, and add the result at the end with the equals sign.

So it virtually means:

"something={executed something}"

From Python 3.8, f-strings support "self-documenting expressions", mostly for print de-bugging. From the docs:

Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression. For example:

user = 'eric_idle'
member_since = date(1975, 7, 31)
f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"

The usual f-string format specifiers allow more control over how the result of the expression is displayed:

>>> delta = date.today() - member_since
>>> f'{user=!s}  {delta.days=:,d}'
'user=eric_idle  delta.days=16,075'

The = specifier will display the whole expression so that calculations can be shown:

>>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
theta=30  cos(radians(theta))=0.866

This is actually a brand-new feature as of Python 3.8.

Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression.

Essentially, it facilitates the frequent use-case of print-debugging, so, whereas we would normally have to write:

f"some_var={some_var}"

we can now write:

f"{some_var=}"

So, as a demonstration, using a shiny-new Python 3.8.0 REPL:

>>> print(f"{foo=}")
foo=42
>>>