Print debugging: 7 ways your output lies
Published
By the Unrust team · 9 min read · Editorial method
Print debugging is fine if you predict the output first. A 5-step method and 7 ways printed output misleads, each re-run in Python, Node and TypeScript.
What is print debugging? The short answer
Print debugging is adding temporary print or console.log calls to see what a program really does. It is a sound way to test one hypothesis if you predict the output first, and it misleads when printing consumes an iterator, output arrives out of order, or two different values print the same.
Below: a five-step method, a worked example, seven traps with exact output, a cheat sheet for Python and JavaScript, and a checklist for leaving no print statements behind. Python leads. JavaScript and TypeScript appear where they behave differently.
The five steps are our own method, not a researched protocol. The outputs are not opinion: we ran every program on November 21, 2026, and the output shown is identical on every version listed next.
Versions run: CPython 3.9.25, 3.10.22, 3.11.2, 3.11.18, 3.12.16, 3.13.18, 3.14.10 and 3.15.2; Node.js 18.20.4, 22.11.0, 22.23.5 and 24.11.0, with the TypeScript example run through tsx 4.22.4. The TypeScript was also type-checked in strict mode with 5.7.3 and 6.0.3.
Step Do this In the worked example
---------------- -------------------------------------------------- -----------------------------------
1 Hypothesis Write one sentence about one cause The divisor counts the None
2 Prediction Write the exact output before you run total=180 len(readings)=3
3 One print Add one labelled print that can prove you wrong print(f"{total=} {len(readings)=}")
4 Run, compare Check the output against the prediction Same text: the hypothesis survives
5 Decide, delete Fix it, or form a new hypothesis; delete the print Divide by the readings you addedIs print debugging bad? When to print, log or use a debugger
No. Print debugging is the right first move when you can rerun the code in seconds and have one hypothesis to test. Use logging for code that keeps running, a debugger when you need many variables at one point, and an assert or a test for a condition that must always hold.
The table is our rule of thumb, not a standard. Outside rules point the same way: Ruff's T201 and ESLint's no-console flag debugging output before it ships, and Ruff's documentation adds that prints which are a command-line tool's real output are not typically a problem.
Situation Reach for Why
-------------------------------------- --------- ---------------------------------------
One hypothesis, quick to rerun print One labelled line answers it; delete it
Unsure which variable is wrong debugger Pause once, read every local
Code that keeps running (service, job) logging Levels and timestamps; switch on or off
A rule that must always hold assert Fails at the line that breaks the rule
A bug you never want back test Keeps checking after the print is gone
Output users are meant to see (CLI) print That is the product, not debuggingWorked example: one hypothesis, one labelled print
mean_reading([80, None, 100]) should return 90.0, the mean of the two real readings, and it returns 60.0. The hypothesis: the loop skips the None correctly, but the divisor still counts it. The prediction, written before the run: total=180 len(readings)=3.
f"{total=} {len(readings)=}" prints each expression next to its value, so the line labels itself. It printed the predicted text, so the hypothesis survives and the cause is the divisor. Had it printed len(readings)=2, you would drop the hypothesis instead of adding a second print.
Step 5 is the fix and the cleanup: divide by the readings you added, then delete the print. The method only works if the output tells the truth. The next seven sections show where it does not.
def mean_reading(readings):
total = 0
for r in readings:
if r is not None:
total += r
print(f"{total=} {len(readings)=}") # total=180 len(readings)=3
return total / len(readings)
# You expect 90.0, the mean of 80 and 100.
print(mean_reading([80, None, 100])) # 60.0
# Fix: divide by the readings you added, and delete the print.
def mean_reading(readings):
valid = [r for r in readings if r is not None]
return sum(valid) / len(valid)
print(mean_reading([80, None, 100])) # 90.0Trap 1: the print consumes the iterator it prints
A zip, map, filter or generator can be read once. A print that expands it with list() reads it for you, and the next line gets nothing.
Without the first print this program works. Predict both printed lines before you open the answer.
names = ["ana", "ben"]
marks = [82, 74]
pairs = zip(names, marks)
print(list(pairs))
report = dict(pairs)
print(report)Reveal the answer and explanation
It prints [('ana', 82), ('ben', 74)] and then {}. list(pairs) read both pairs, so dict(pairs) found nothing left and built an empty dict without raising an error.
Printing pairs itself shows only its type and a memory address in angle brackets, as in zip object at 0x7f..., and the address can differ on every run. The fix is to build the list once, print that list and pass the same list on, as below.
A file object behaves the same way: print(f.read()) reads to the end, so a second f.read() returns an empty string. Our post on exhausted iterators and mutable defaults traces the mechanism line by line.
names = ["ana", "ben"]
marks = [82, 74]
pairs = list(zip(names, marks)) # materialize once, reuse everywhere
print(pairs) # [('ana', 82), ('ben', 74)]
report = dict(pairs)
print(report) # {'ana': 82, 'ben': 74}Trap 2: two different values print the same text
print() converts each argument with str(), which is written for readers, so values that differ can print identically. A trailing space, the integer 1 against the string "1", and a comma inside a value all disappear into the output.
Print the repr instead. f"{x=}" shows the expression, an equals sign and repr(x), so spaces and quotes appear. The = specifier arrived in Python 3.8.
Node.js has the same problem and a similar fix. console.log(1, "1") prints 1 1, while console.log({ x }) prints the name and the quoted value: { x: '5 ' }.
x = "5 "
print(x, len(x)) # 5 2
print(f"{x=}") # x='5 '
print(1, "1") # 1 1
print([1, "1"]) # [1, '1']
row = ["a,b", "c"]
print(",".join(row)) # a,b,c
print(row) # ['a,b', 'c']Trap 3: buffered output arrives out of order
When a program writes to both stdout and stderr, redirecting it can change the order you see. Python line-buffers stdout only when it is interactive; through a pipe or into a file stdout is block-buffered, while stderr is line-buffered in both cases.
Predict the order of the three lines in a terminal, and when the program runs as python order.py 2>&1 | cat, which sends both streams down one pipe.
# order.py
import sys
print("out 1")
print("err 1", file=sys.stderr)
print("out 2")Reveal the answer and explanation
In a terminal the lines appear as written: out 1, err 1, out 2. Through the pipe they come out as err 1, out 1, out 2, because the stdout lines wait in a buffer until the program exits while the stderr line is written at once. Every CPython version we ran gave the same orders.
Fix it with python -u, the PYTHONUNBUFFERED environment variable, or flush=True on the prints that matter. Buffering can also lose output: a program that prints and then calls os._exit(1) shows nothing through a pipe, because os._exit skips flushing the buffers, and the same program run with -u shows the line.
# order.py, with flush=True on the stdout prints
import sys
print("out 1", flush=True)
print("err 1", file=sys.stderr)
print("out 2", flush=True)
# $ python order.py 2>&1 | cat
# out 1
# err 1
# out 2Trap 4: Node.js hides nested values behind [Object]
console.log passes objects to util.inspect, and util.inspect stops recursing after two levels by default. Anything deeper prints as [Object] or [Array], so the field you are hunting for may be exactly the one that is hidden.
Concatenation is worse: "order: " + order calls toString(), which gives [object Object] and nothing else. Pass the object as its own argument, print JSON.stringify(order), or use console.dir(order, { depth: null }).
JSON.stringify shows every level, but it is lossy in its own way: it drops undefined values and functions, and it prints NaN as null.
const order = { id: 7, items: [{ sku: "A1", opts: { gift: { wrap: true } } }] };
console.log(order); // { id: 7, items: [ { sku: 'A1', opts: [Object] } ] }
console.log("order: " + order); // order: [object Object]
console.log(JSON.stringify(order)); // {"id":7,"items":[{"sku":"A1","opts":{"gift":{"wrap":true}}}]}
console.dir(order, { depth: null });
// {
// id: 7,
// items: [
// { sku: 'A1', opts: { gift: { wrap: true } } }
// ]
// }Trap 5: async output shows completion order, not source order
Logs from asynchronous code show the order in which callbacks ran, not the order of the lines in the file. A timer callback and a promise callback written in one order can run in the other.
Predict the four lines this prints in Node.js before you open the answer.
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");Reveal the answer and explanation
It prints A, D, C, B. The two synchronous logs run first. The promise callback runs next, as a microtask, and the timer callback runs after it, even though its delay is 0.
To debug an ordering problem, log twice: where the work is scheduled and where it runs. The labelled version below prints A, B scheduled, C scheduled, D, C ran, B ran, so the gap between scheduling and running is visible.
console.log("A");
setTimeout(() => console.log("B ran"), 0);
console.log("B scheduled");
Promise.resolve().then(() => console.log("C ran"));
console.log("C scheduled");
console.log("D");
// Output:
// A
// B scheduled
// C scheduled
// D
// C ran
// B ranTrap 6: two names, one object
A function that mutates its argument changes the very object the caller's variable points to, so printing that variable shows a change you did not make there. The two names look like two lists but are one object.
Print the identity, not only the contents: priced is cart is True. The second version builds a new list, so the original keeps its two items.
Our post on exhausted iterators and mutable defaults covers the related trap of a default list shared between calls.
def with_total(prices):
prices.append(sum(prices))
return prices
cart = [5, 7]
priced = with_total(cart)
print(cart) # [5, 7, 12]
print(priced is cart) # True
def with_total_copy(prices):
return [*prices, sum(prices)]
cart = [5, 7]
priced = with_total_copy(cart)
print(cart, priced) # [5, 7] [5, 7, 12]Trap 7: no output is ambiguous, so print before the branch
A silent run tells you less than it seems to. Either the line never ran, or it ran and the output went somewhere else. Print the inputs to the decision before the branch, not only inside it.
The compiler accepts the TypeScript below because the cast says qty is a number. At runtime JSON.parse returned the string "3", so qty === 3 is false and the branch prints nothing. Printing qty shows 3 either way; typeof shows string.
Check the other silent causes in this order: print __file__ and sys.executable to confirm which file and interpreter ran; run pytest with -s or -rP, because pytest 9.2.0 hides the output of passing tests by default; and see trap 3 for output lost at exit.
type Order = { id: number; qty: number };
// The cast tells the compiler to trust the JSON. Nothing checks it at runtime.
const order = JSON.parse('{"id": 7, "qty": "3"}') as Order;
if (order.qty === 3) {
console.log("three items"); // never runs, so nothing prints
}
console.log(order.qty); // 3
console.log(typeof order.qty); // stringHow do you print debug in Python and JavaScript?
In Python, print(f"{x=}") labels the value and print(repr(x)) shows quotes and spaces. In JavaScript, console.log({ x }) labels the value and console.dir(x, { depth: null }) prints every level. Send debug output to stderr with print(x, file=sys.stderr) in Python or console.error(x) in JavaScript.
One caution on console.log({ x }): the wrapper adds a level, so Node.js cuts a nested value one level earlier. For the object in trap 4, console.log({ order }) prints { order: { id: 7, items: [ [Object] ] } }.
Need Python JavaScript / TypeScript
----------------------------- ------------------------- -------------------------------
Label and value print(f"{x=}") console.log({ x })
Quotes and spaces visible print(repr(x)) console.log(JSON.stringify(x))
Every level of a nested value print(x) console.dir(x, { depth: null })
Write to stderr print(x, file=sys.stderr) console.error(x)
Show the type print(type(x)) console.log(typeof x)Leave no prints behind: a before-you-commit checklist
Tag every temporary print with one marker such as DBG, search for the marker before you commit, and let a linter catch what the search misses. If you will need a line again, turn it into a logging call or a test instead of leaving a print.
Ruff reports each leftover print as T201, and ESLint's no-console rule reports console calls as Unexpected console statement. Both rules must be enabled in your configuration; they behaved as described on Ruff 0.17.6 and ESLint 9.39.5.
A forgotten breakpoint() is the other leftover: it stops the program at a debugger prompt. Setting PYTHONBREAKPOINT=0 makes every breakpoint() call do nothing.
Step Python JavaScript / TypeScript
--------------------------- ------------------------ -----------------------
Tag the temporary print print("DBG", x) console.log("DBG", x)
Search for the tag git grep -n DBG git grep -n DBG
Lint what the search missed ruff check --select T201 ESLint rule no-console
Keep a line you will need logging.debug("x=%s", x) a logger, or a testIs it okay to use AI to debug code?
Yes, if you make the first pass yourself. Write your hypothesis and the output you expect, read the error message, and run one print or breakpoint before you ask. Then give the assistant your evidence, the code plus the expected and actual output, and verify its suggestion with another run.
The prediction is the cheapest test of whether you understand the code. If you paste the failure into an assistant first, you never learn whether your own reading was right, and a wrong prediction is the clearest sign that your picture of the code needs fixing.
This is a working habit, not a claim about what AI does to your skills. Our guide to debugging without AI covers using an assistant for alternatives once you have a diagnosis, and our post on keeping your skills while using AI covers what research does and does not show.
To see how you debug when the assistant is off, the free diagnostic covers tracing and debugging among its skills. It takes about 14 minutes with AI off and needs no account.
Print debugging questions
What is print debugging, and what is print() called in Python? Print debugging means adding temporary print statements or other output calls to watch a program's state as it runs. It is also called printf debugging, after C's printf function. In Python 3, print() is a built-in function, not a statement: print(x) writes str(x) to sys.stdout unless you pass file=.
When should you switch from print to a debugger? Switch when a second or third print would only be a guess about where to look: you need many variables at one point, or you cannot predict which one matters. In Python, breakpoint() pauses at that line in pdb. In Node.js, run node inspect script.js, or use your editor's debugger.
Why does my print show nothing? Either the line never ran, or the output went elsewhere. Print the inputs before the branch, print __file__ to confirm which file ran, run pytest with -s because it hides the output of passing tests, and use python -u if the process can exit before its buffer is flushed.
Why does Python print out of order? When stdout goes to a pipe or a file, Python block-buffers it while stderr stays line-buffered, so stderr lines can appear before earlier stdout lines. Run python -u, set PYTHONUNBUFFERED=1, or pass flush=True to print, and the order matches the order of the calls.
Why does console.log show [Object]? Node.js formats objects with util.inspect, which stops recursing after two levels by default and prints [Object] for anything deeper. Use console.dir(obj, { depth: null }) or JSON.stringify(obj, null, 2) to see every level, and pass objects as separate arguments instead of joining them to a string.
References and next steps
- Python documentation: sys.stdout and buffering
- Python documentation: built-in functions (print, repr, breakpoint)
- Node.js documentation: util.inspect
- Unrust blog: Python debugging exercises: 10 bugs to fix
- Unrust guide: What is code tracing?
- Unrust: Python Debugging Practice for Developers
- Unrust: JavaScript Debugging Practice for Developers
- Unrust: TypeScript Debugging Practice for Developers
- Unrust blog: Trace exhausted Python iterators and shared mutable defaults
- Unrust blog: Separate the first symptom from the root cause in service logs
- Unrust blog: How do I keep my coding skills while using AI?
- Debug without AI: shrink the failure and test one hypothesis
Check how you debug with AI off
Take Unrust's free diagnostic with AI and hints closed: a warm-up, a few short drills that include tracing and debugging, and a per-skill read at the end. About 14 minutes, no account needed.
More from the blog
- Debugging interview: 6 steps and a mock round
Debugging & logs · 12 min read
- How to read a stack trace in Python and Node
Debugging & logs · 10 min read
- Code review interview: a rubric and 4 diffs
Code review · 10 min read