brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's f"{x=}" prints the variable name and its value in one go

Python
~/tips/tip-python-fstring-equals-debug

name = "jellyfin"

Prints both the expression and its value, so debug output labels itself.

I still reach for a quick print() when a Python script does something odd, and the annoying part was always typing the label: print("count:", count). Since Python 3.8 an f-string can write that label for you. Put an equals sign after the expression and you get the expression’s own text, an =, and the value.

Here’s the short version:

count = 42
name = "jellyfin"
print(f"{count=} {name=}")

That prints count=42 name='jellyfin'. Notice the quotes around the string: with the debug specifier and no format spec, Python uses repr() of the value, which is exactly what you want while debugging. You can see straight away whether something is the string '42' or the number 42, or whether a value has a sneaky trailing space.

It works for whole expressions too, which is where I like it best. The text you typed is printed as is, so you can check a calculation and its result on one line:

size = 1536000
print(f"{size / 1024 / 1024 = :.2f}")

That gives size / 1024 / 1024 = 1.46. You can also combine it with the usual tricks: !s forces str() instead of repr(), and anything after the colon is a normal format spec, like :,d for thousands separators.

One caveat that trips people up: whitespace inside the braces is kept in the output. f"{ count = }" prints count = 42, spaces included. That’s handy when you want it readable, odd when you didn’t expect it. And once you add a format spec like :.2f, the default switches from repr() to the formatted value, so you lose the quotes around strings. Add !r if you want them back.

My advice is to make this your default debug print and delete those lines before you commit. For anything that stays in the code, a proper logger is still the better home.

Further reading: Python docs: f-string debug specifier, What's New in Python 3.8: f-strings support =

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link