Stop Guessing Values: Master Python’s f-String Debugging
Introduction
Tired of sprinkling print statements everywhere just to peek at a variable’s content? In this quick tip we’ll show you Python’s f–string debugging feature, introduced in Python 3.8, that prints both the variable name and its value in a single, readable line. No manual string concatenation, no extra mental overhead – just drop an = inside the braces and let Python do the work.
The Core Syntax
The new f–string syntax is remarkably simple:
value = 42
print(f"{value=}") # → value=42
Placing an equals sign after the expression inside the curly braces tells Python to evaluate the expression and prepend the source text (value) followed by = and the resulting value. This works with any valid expression, not just plain variables.
Real–World Use Cases
1. Inside Loops
When iterating, you often need to watch the loop variable and intermediate state:
for i in range(3):
square = i * i
print(f"{i=}, {square=}")
Output:
i=0, square=0
i=1, square=1
i=2, square=4
This keeps the loop body tidy while giving you instant visibility.
Best Practices & Pitfalls
| Good Practice | Pitfall |
|---|---|
| Use only for temporary debugging – strip the statements before committing production code. | Leaving debug f–strings in production can leak internal state or clutter logs. |
| Combine related variables in a single f–string to reduce noise. | Over–using in tight loops may impact performance; consider logging.debug for high–frequency traces. |
| Leverage in REPL or notebooks where quick feedback is valuable. | Assuming older Python versions support it – the feature requires Python 3.8+. |
Related Posts
Packaging Made Easy: A Step-by-Step Guide to Using Setuptools and Twine for PyPI
Simplify Python project packaging with setuptools and Twine for PyPI
Mastering Isolated Python Environments with Venv and Pip
Learn to create isolated Python environments with venv and manage packages with pip
Mastering Error Handling in Python with Try/Except Blocks
Learn to use try/except blocks to handle errors in Python
Mastering OOP Basics in Python: Classes, Inheritance, and the Factory Pattern
Learn Python OOP fundamentals—defining classes, adding methods, inheritance, and a simple Factory pattern—in a concise, example‑driven guide.