Sub topic 9
Quick debugging with f"{x=}"
This chapter covers the = specifier in f-strings. It prints an expression's source text next to its value, which makes it a fast replacement for hand-written debug prints. It assumes you can write basic f-strings and know the !r conversion and the : format spec from the earlier chapters. It also assumes Python 3.8 or newer, because the feature was added in 3.8.
The problem it solves
When a program misbehaves, a common first step is to print a few values. The usual version has a repetitive shape:
x = 7
print("x =", x)
print("x * 2 =", x * 2)You type each name twice, once as a label and once as the value. Labels drift out of sync when you edit the code, and a forgotten label leaves you looking at a bare number with no idea where it came from.
Adding = after the expression inside the braces removes the duplication:
x = 7
print(f"{x=}")
print(f"{x * 2 = }")This prints:
x=7
x * 2 = 14Python takes the text you wrote inside the braces, appends =, and then appends the value. The label is the code itself, so it cannot drift from the expression.
How the output is built
The = is not a separate operator. It is a marker on the replacement field that asks Python to emit the expression's source text first. A replacement field with the marker has this order:
{ expression = !conversion :format_spec }
The conversion and the format spec are both optional, but they must come after the =.
Two details follow from this:
- The text is copied verbatim, including any spaces around the
=. That is why{x * 2 = }printsx * 2 = 14while{x*2=}printsx*2=14. - The expression is evaluated once. A call such as
f"{next(it)=}"consumes exactly one item.
Spacing is part of the output
Whitespace you put around the = appears in the result. Use it to match the style you prefer.
| Source | Output with `x = 7` |
|---|---|
| `f"{x=}"` | `x=7` |
| `f"{x = }"` | `x = 7` |
| `f"{x =}"` | `x =7` |
| `f"{x= }"` | `x= 7` |
| `f"{x * 2=}"` | `x * 2=14` |
Pick one style and keep it. Most people use {x=} for names and {expr = } for longer expressions, where the spaces make the output easier to read.
Debugging several values at once
You can put more than one field in a single string. This gives you a snapshot of related variables on one line:
def average(values):
total = sum(values)
count = len(values)
print(f"{total=} {count=}")
return total / count
print(average([4, 8, 15]))This prints:
total=27 count=3
9.0The expression can be anything valid in a replacement field: attribute access, indexing, calls, comparisons, and arithmetic.
items = [3, 1, 2]
config = {"retries": 5}
print(f"{len(items)=}")
print(f"{items[0]=}")
print(f"{sorted(items)=}")
print(f"{config['retries'] > 3 = }")
print(f"{0.1 + 0.2 = }")This prints:
len(items)=3
items[0]=1
sorted(items)=[1, 2, 3]
config['retries'] > 3 = True
0.1 + 0.2 = 0.30000000000000004The last line shows the main strength of the feature. The value is shown with repr(), so you see the full float rather than a rounded display.
Why the default is repr()
If you give no conversion and no format spec, = formats the value with repr(). This is a good default for debugging, because repr() shows the details that str() hides. Strings get quotes, and escape sequences stay visible:
raw = "42\n"
name = "Ada\tLovelace"
print(f"{raw=}")
print(f"{name=}")
print(f"{name=!s}")This prints:
raw='42\n'
name='Ada\tLovelace'
name=Ada LovelaceThe first line exposes a trailing newline that a plain print(raw) would hide as an unexplained blank line. The third line uses !s to ask for str() instead. The tab is then printed as real whitespace.
Combining = with a format spec
Adding a format spec changes the default. When you write a spec and no conversion, Python uses format(value, spec), the same path as a normal f-string, rather than repr(). The label still appears before the value.
price = 1234.5
label = "total"
print(f"{price=}")
print(f"{price=:,.2f}")
print(f"{price = :>12,.2f}")
print(f"{label=:>10}")
print(f"{label=!r:>10}")This prints:
price=1234.5
price=1,234.50
price = 1,234.50
label= total
label= 'total'Read the last two lines closely. With only a spec, the string is padded without quotes. With !r before the spec, the value is converted by repr() first, so the quotes are included in the width. The rule to remember is that a spec switches the default from repr() to format(), and an explicit conversion overrides that choice.
Quoting and nesting
The label is copied from your source, so any quotes in the expression appear in the output. Before Python 3.12, you could not reuse the outer quote character inside the braces, so you had to alternate:
config = {"mode": "fast"}
print(f"{config['mode']=}")This prints:
config['mode']=fastThe output shows fast without quotes, but wait: the default is repr(), so the value should be quoted. The correct output is:
config['mode']='fast'The label uses the single quotes you wrote, and the value is the repr() of the string, which also uses single quotes. In Python 3.12 and later you can write f"{config["mode"]=}", and the label then shows the double quotes exactly as typed.
Sending debug output somewhere useful
A debug print is still a print, so it goes to standard output and mixes with your program's real output. If the script's output is piped or redirected, send the debug lines to standard error instead:
import sys
def parse_port(text):
print(f"{text=}", file=sys.stderr)
port = int(text)
print(f"{port=}", file=sys.stderr)
return port
print(parse_port("8080"))Running python script.py > out.txt leaves only 8080 in the file, while the two debug lines still appear in the terminal.
Limits and gotchas
- Only f-strings support it.
str.format()and%formatting have no equivalent. Writing"{x=}".format(x=7)raises aKeyErrorbecausex=is treated as a field name. - Side effects run once, but they still run.
f"{items.pop()=}"removes an item. Do not debug with expressions that change state unless that is the point. - Spaces inside the expression are preserved. If you reformat the code, the output text changes with it.
- Long values are not truncated.
f"{big_list=}"prints the whole list. Slice it (f"{big_list[:5]=}") when the object is large. - It is a debugging aid, not logging. Remove these lines before shipping, or turn them into proper logging calls. A search for
=}in your editor finds leftovers quickly. - Custom classes need a good
__repr__. The defaultrepr()of an instance shows only the type and a memory address. Defining__repr__makes=output useful.
Summary
The = specifier turns f"{expr=}" into the expression's source text, an equals sign, and the formatted value. By default the value comes from repr(). A format spec switches it to format(), and !s, !r, or !a selects a conversion explicitly. Whitespace around the = is copied to the output. It needs Python 3.8 or newer and works only in f-strings.
Exercise
Given n = 5 and word = "hi", what does print(f"{n * 3 = } {word=}") print, and what does print(f"{word=!s:>6}") print?
Show answer
The first prints n * 3 = 15 word='hi'. The text of the expression and the spaces around = are copied, and the string value uses repr, so it has quotes. The second prints word= hi. The !s conversion removes the quotes, and the spec >6 right-aligns hi in a field of width 6, giving four leading spaces after the =.
Exercise
A script reads a line with line = input() and then int(line) fails with ValueError. You suspect the input has hidden characters. Write one f-string debug line that would reveal them, and say why print(line) would not.
Show answer
Use print(f"{line=}"). It shows the repr() of the string, so a trailing space prints as '42 ', a tab as '42\t', and a carriage return as '42\r'. print(line) uses str(), which writes those characters as invisible whitespace, so the problem cannot be seen.
Exercise
You write f"{ratio=:.1%}" with ratio = 0.256. What is printed, and what would be printed by f"{ratio=!r:.1%}"?
Show answer
The first prints ratio=25.6%, because the spec applies to the float through format(). The second raises a TypeError, because !r converts the value to a string first and the .1% spec is not valid for strings.