PythonMastery

Label your debug prints with f"{x=}"

f"{price=}" prints price=4.5: the name and the value, with no typing it twice. It works on whole expressions and with format specs like f"{price=:.2f}".

A debug print without labels gives you a row of values and a guessing game. f"{name=}" (Python 3.8 and later) prints the name, an equals sign and the value, so you never type the name twice or mix two prints up.

Before

python
order_id = "A-1002"
quantity = 3
price = 4.5

print(order_id, quantity, price * quantity)
print("order_id:", order_id, "quantity:", quantity)
output
A-1002 3 13.5
order_id: A-1002 quantity: 3

The first line is ambiguous by the time there are four of them. The second is right, but you typed every name twice, and one day the label and the variable won't match.

After

python
order_id = "A-1002"
quantity = 3
price = 4.5

print(f"{order_id=} {quantity=} {price * quantity=}")
output
order_id='A-1002' quantity=3 price * quantity=13.5

It works on whole expressions, not just names: price * quantity= shows the sum you actually wrote. Strings come out with their quotes, which tells you straight away that order_id is text, not a number.

Formats still work

Put the format spec after the =, exactly where it normally goes:

python
price = 4.5
order_id = "A-1002"

print(f"{price=:.2f}  {order_id=!s}")
output
price=4.50  order_id=A-1002

!s drops the quotes when you'd rather have them off; without it, = uses repr(), which is usually what you want while debugging (why).

Why it works

When Python sees = at the end of an f-string field, it keeps the source text of the expression and prints it before the value. Spaces are kept too: f"{price = }" prints price = 4.5.

When not to use it

It's a debugging tool. Output meant for people reading the program's results should say what things mean ("Total: £13.50"), not what the variables are called. And once a debug print has done its job, delete it, or turn it into a proper log message.

Learn it properly: F-Strings: Modern String Formatting