Skip to content

Mojo Debugging

Your program runs, but the answer is wrong. Or it crashes, and you don’t know why. Debugging is the work of finding out what really happens inside, step by step. This lesson starts with the simplest tool (a well-placed print) and works up to a real debugger. You’ll use the simple ones far more often than you’d think.

Here’s a program with a bug. The average of 90, 85 and 72 should be about 82.33:

def average(nums: List[Int]) -> Float64:
var total = 0
for n in nums:
total += n
return Float64(total / len(nums))
def main():
var scores: List[Int] = [90, 85, 72]
print("average:", average(scores))

Output:

average: 82.0

Where did the .33 go? The quickest way to find out is to print the values along the way. Send debug prints to standard error (file=stderr), so they don’t mix with your program’s real output:

from std.sys import stderr
def average(nums: List[Int]) -> Float64:
var total = 0
for n in nums:
total += n
print("debug: total =", total, "count =", len(nums), "total / count =", total / len(nums), file=stderr)
return Float64(total / len(nums))
def main():
var scores: List[Int] = [90, 85, 72]
print("average:", average(scores))

You’ll see:

debug: total = 247 count = 3 total / count = 82
average: 82.0

There it is: total / count is 82, not 82.33. In Mojo, / between two Int values gives an Int (see Mojo Operators), and turning 82 into a float afterwards can’t bring the decimals back. The fix is to convert before dividing: Float64(total) / Float64(len(nums)) gives 82.33333333333333.

Instead of adding and deleting prints, you can keep them in the code behind a switch that’s off by default:

from std.sys import is_defined, stderr
def total(prices: List[Int]) -> Int:
var sum = 0
for p in prices:
comptime if is_defined["TRACE"]():
print(" adding", p, "sum so far", sum, file=stderr)
sum += p
return sum
def main():
var prices: List[Int] = [3, 5, 9]
print("total:", total(prices))

Output:

total: 17

Now turn the switch on with -D TRACE:

Terminal window
mojo run -D TRACE trace.mojo
adding 3 sum so far 0
adding 5 sum so far 3
adding 9 sum so far 8
total: 17

comptime if decides at compile time. Without -D TRACE, the print isn’t just skipped, it isn’t in the program at all, so it costs nothing. Mojo Feature Toggles explains -D and is_defined in detail.

Many bugs show up earlier, and with a clearer message, when all of Mojo’s asserts are on. While you’re hunting a bug, run with:

Terminal window
mojo run -D ASSERT=all app.mojo

That switches on every debug_assert and assert, in your code and in the standard library. See Mojo Debug Asserts for how they work.

When a program crashes on a failed check, the first line already tells you where:

def last_item(xs: List[Int]) -> Int:
return xs[len(xs)]
def main():
var xs: List[Int] = [4, 8, 15]
print(last_item(xs))

You’ll see:

At: crash.mojo:2:14: Assert Error: index 3 is out of bounds, valid range is 0 to 2
...
mojo: error: execution crashed

Line 2, column 14: xs[len(xs)]. A list of 3 items has indexes 0 to 2, so the last one is xs[len(xs) - 1].

For a raised error that nobody catches, you only get the message by default. To see which functions it passed through, build with debug info and run with MODULAR_DEBUG=stack-trace-on-error:

Terminal window
mojo build -g app.mojo
MODULAR_DEBUG=stack-trace-on-error ./app

The Mojo Errors lesson shows what that trace looks like and how to read it.

A debugger lets you pause a running program at a line you choose (a breakpoint), look at every variable, and then go on one line at a time. Mojo comes with one: the mojo package includes the LLDB debugger with Mojo support, started with mojo debug.

You can point mojo debug at a .mojo file, and it builds the program with debug info for you. Or build it yourself first, with -O0 -g (no optimization, full debug info), which is what the docs recommend for the best results. Let’s debug this file, prices.mojo:

def total(prices: List[Int]) -> Int:
var sum = 0
for p in prices:
sum += p
return sum
def main():
var prices: List[Int] = [3, 5, 9]
var t = total(prices)
print("total:", t)

Output:

total: 17

Build it and start the debugger:

Terminal window
mojo build -O0 -g prices.mojo
mojo debug ./prices

You get an (lldb) prompt where you type commands. Here’s a session we ran, a little trimmed (the # notes are ours):

(lldb) b prices.mojo:4 # stop every time line 4 runs
Breakpoint 1: where = prices`prices::total(...) + 200 at prices.mojo:4:13
(lldb) run # start the program
* thread #1, name = 'prices', stop reason = breakpoint 1.1
frame #0: prices`prices::total(prices=(size 3)[3, 5, 9]) at prices.mojo:4:13
3 for p in prices:
-> 4 sum += p
5 return sum
(lldb) p sum # print a variable
(__mlir_type.`!kgen.scalar<index>`) 0
(lldb) p p
(__mlir_type.`!kgen.scalar<index>`) 3
(lldb) continue # run to the next breakpoint
(lldb) p sum
(__mlir_type.`!kgen.scalar<index>`) 3
(lldb) bt # how did we get here?
* frame #0: prices`prices::total(prices=(size 3)[3, 5, 9]) at prices.mojo:4:13
frame #1: prices`prices::main() at prices.mojo:9:18
(lldb) quit

The type names in brackets look strange (Int shows up as an internal type), but the values are right: after the first pass through the loop, sum went from 0 to 3. The commands you’ll use most:

Command What it does
b file.mojo:4 Set a breakpoint on line 4
run Start the program
p name Print a variable (frame variable prints all of them)
next Run the current line, without going into functions it calls
step Run the current line, going into a function it calls
finish Run until the current function returns
continue Run until the next breakpoint
bt Show the call stack: which function called which
quit Stop debugging

If you’d rather click than type, the Mojo extension for VS Code uses the same debugger behind a normal VS Code debugging screen. We haven’t run it for this page, so here’s what the official debugging guide describes:

  • Open a Mojo file with a main and choose Debug Mojo File from the Run or Debug button in the editor toolbar (or press F5).
  • Click in the left margin to set breakpoints. Local variables show up inline and in the Variables panel, and the Call Stack panel shows how you got there.
  • Turn on the Mojo Raise breakpoint to stop whenever a raise statement runs.
  • mojo debug --vscode app.mojo starts a session in an open VS Code window from the terminal.

The guide also lists current limits: breakpoints with a condition expression aren’t supported (hit counts are), and the return value isn’t shown when you step out of a function.

You can also put a breakpoint in the code itself, with the built-in breakpoint(). Under a debugger, the program pauses there. Without a debugger, it crashes:

def main():
print("before")
breakpoint()
print("after")

You’ll see:

before
mojo: error: execution crashed

So don’t leave a bare breakpoint() in your code. A safer pattern is to put it behind a switch, so it’s only there when you ask for it:

from std.sys import is_defined
def main():
var count = 3
comptime if is_defined["DEBUG_ME"]():
breakpoint()
print("count:", count)

Output:

count: 3

mojo debug -D DEBUG_ME app.mojo then stops at that line, while a normal mojo run never sees the breakpoint().

This function should add up the numbers from 1 to n, so sum_to(4) should be 10. It prints 6. Add a debug print to stderr inside the loop to see which numbers it adds, then fix it.

def sum_to(n: Int) -> Int:
var total = 0
for i in range(1, n):
total += i
return total
def main():
print(sum_to(4))

Hint: print i each time round the loop. Which number is missing?

Show solution
def sum_to(n: Int) -> Int:
var total = 0
for i in range(1, n + 1):
total += i
return total
def main():
print(sum_to(4))

Output:

10

The debug print shows 1, 2, 3 and no 4: range(1, n) stops before n. range(1, n + 1) includes it.

Take the fixed sum_to and add a -D TRACE switch that prints adding <i> to stderr for each number, only when the switch is on. Without it, the program prints only 10.

Hint: from std.sys import is_defined, stderr and comptime if is_defined["TRACE"]():.

Show solution
from std.sys import is_defined, stderr
def sum_to(n: Int) -> Int:
var total = 0
for i in range(1, n + 1):
comptime if is_defined["TRACE"]():
print("adding", i, file=stderr)
total += i
return total
def main():
print(sum_to(4))

Output:

10

With mojo run -D TRACE sum.mojo you also see adding 1 to adding 4 before the 10.

  • Start with print debugging: print labels and values, to stderr, one guess at a time.
  • Keep debug output behind a comptime if is_defined["TRACE"]() switch and turn it on with -D TRACE.
  • Run with -D ASSERT=all while hunting bugs so every check is on.
  • A failed check prints file:line first; for raised errors, use mojo build -g plus MODULAR_DEBUG=stack-trace-on-error.
  • mojo debug starts LLDB: b, run, p, next, step, continue, bt. Build with -O0 -g first for the best results.
  • VS Code’s Mojo extension wraps the same debugger; a bare breakpoint() crashes without a debugger.

Next up: feature toggles, the -D switches and compile-time checks in more detail.

Quick check

1. Why print debug messages with file=stderr?
2. What do the -O0 -g options do when you build a program to debug?
3. What happens if a program calls breakpoint() while it's not running under a debugger?
4. In an LLDB session, which command runs until the next breakpoint?