Mojo Debug Asserts
Errors are for problems you expect: bad input, a missing file. But some things should simply never happen if your code is right, like a negative grid size coming out of your own function. When they do happen, that’s a bug. Mojo’s debug_assert lets you write those “this must be true” checks into your code, and you choose when they run. This lesson shows how, and how a failed check differs from an error.
Your first debug_assert
Section titled “Your first debug_assert”debug_assert(condition, message...) checks a condition. If it’s false, the program prints the message and stops. It’s built in, so there’s nothing to import:
def cell_count(width: Int, height: Int) -> Int: debug_assert(width > 0 and height > 0, "bad grid size: ", width, " x ", height) return width * height
def main(): print("grid has", cell_count(4, 3), "cells") print("grid has", cell_count(-2, 3), "cells") print("done")Output:
grid has 12 cellsgrid has -6 cellsdoneWait: -6 cells, and no complaint? That’s on purpose. Normal debug asserts are off by default. They cost a little time on every call, so Mojo only runs them when you ask. To turn them on, pass -D ASSERT=all when you run (or build) the program:
mojo run -D ASSERT=all grid.mojogrid has 12 cellsAt: grid.mojo:2:17: Assert Error: bad grid size: -2 x 3...mojo: error: execution crashedNow the bad call is caught, with the file, line and your message. We cut a few lines of raw addresses (the ...); you’ll learn to read those in Mojo Debugging.
The -D part is a compile-time setting. You’ll see more of those in Mojo Feature Toggles.
The short form: assert
Section titled “The short form: assert”Mojo also has an assert statement that looks like Python’s. It behaves like a plain debug_assert: off by default, on with -D ASSERT=all:
def main(): var stock = 5 var sold = 8 var left = stock - sold assert left >= 0, "sold more than we had" print("left:", left)Output:
left: -3With mojo run -D ASSERT=all, the same program stops:
At: stock.mojo:5:17: Assert Error: sold more than we had...mojo: error: execution crashedAssert levels
Section titled “Assert levels”-D ASSERT=... takes four values:
| Setting | What runs |
|---|---|
-D ASSERT=none |
No asserts at all |
-D ASSERT=safe (the default) |
Only asserts marked assert_mode="safe" |
-D ASSERT=all |
Every assert |
-D ASSERT=warn |
Every assert, but a failure only prints a message and the program keeps going |
warn is handy when you want to see every problem in one run instead of stopping at the first:
mojo run -D ASSERT=warn grid.mojogrid has 12 cellsAt: grid.mojo:2:17: Assert Error: bad grid size: -2 x 3grid has -6 cellsdoneNote that -g (debug info) and -O0 (no optimization) don’t change which asserts run. Only -D ASSERT does. The feature toggles page in the Mojo docs spells this out.
Asserts that are always on
Section titled “Asserts that are always on”Some checks are cheap and important enough to keep in every build. Mark them with assert_mode="safe", and they run by default:
def set_volume(level: Int): debug_assert[assert_mode="safe"]( level >= 0 and level <= 10, "volume must be 0 to 10, got ", level ) print("volume set to", level)
def main(): set_volume(7) set_volume(42) print("done")You’ll see:
volume set to 7At: volume.mojo:2:37: Assert Error: volume must be 0 to 10, got 42...mojo: error: execution crashedThe square brackets [assert_mode="safe"] pass a compile-time setting to debug_assert. Only -D ASSERT=none turns this one off.
The standard library does exactly this for list indexes. Reading past the end of a List is checked by a “safe” assert, so it stops your program instead of reading random memory:
def main(): var xs: List[Int] = [1, 2, 3] var i = 5 print(xs[i])You’ll see:
At: index.mojo:4:13: Assert Error: index 5 is out of bounds, valid range is 0 to 2...mojo: error: execution crashedWith -D ASSERT=none, that same program printed 0 for us, a value that isn’t in the list at all. That’s why none is risky: the check is gone, but the bug isn’t.
Crashes are not errors
Section titled “Crashes are not errors”Look at the last line of each failed assert: “execution crashed”. An assert doesn’t raise an error. It stops the whole program on the spot, and try can’t catch it:
def main(): var xs: List[Int] = [1, 2, 3] var i = 5 try: print(xs[i]) except e: print("caught:", e)hello.mojo:7:15: warning: 'except' logic is unreachable, try doesn't raise an exception print("caught:", e) ^hello.mojo:6:12: warning: variable 'e' was never used, remove it? except e: ^At: hello.mojo:5:17: Assert Error: index 5 is out of bounds, valid range is 0 to 2mojo: error: execution crashedMojo even warns you: nothing in that try raises. So which one should you use?
raise an error |
debug_assert / assert |
|
|---|---|---|
| For | Problems that can happen in a correct program (bad input, missing file) | Bugs: things that are impossible if your code is right |
| Can be caught | Yes, with try/except |
No, the program stops |
| Runs | Always | Only when its assert level is on |
Function needs raises |
Yes | No |
If you’re not sure, ask: “could a user cause this?” If yes, raise an error. If only a programmer’s mistake can cause it, assert.
Keeping checks cheap
Section titled “Keeping checks cheap”Even when an assert is off, Mojo still works out the condition you pass in. For a quick comparison like level >= 0 that doesn’t matter. For an expensive check, like walking through a whole list, it does. Put the check in a small function instead, and debug_assert only calls it when asserts are on:
def is_sorted(xs: List[Int]) -> Bool: for i in range(1, len(xs)): if xs[i - 1] > xs[i]: return False return True
def middle(xs: List[Int]) -> Int: def check() {xs} -> Bool: return is_sorted(xs) debug_assert(check, "middle() needs a sorted list") return xs[len(xs) // 2]
def main(): var good: List[Int] = [1, 4, 9] var bad: List[Int] = [9, 1, 4] print(middle(good)) print(middle(bad))Output:
41check is a nested function that captures xs (the {xs} part, see Mojo Closures). By default it’s never called, so the sorted check costs nothing. With -D ASSERT=all, the second call stops with Assert Error: middle() needs a sorted list.
Checks at compile time: comptime assert
Section titled “Checks at compile time: comptime assert”When the condition only depends on values the compiler already knows, you can check it while compiling, before the program even runs:
comptime MAX_PLAYERS = 0
def main(): comptime assert MAX_PLAYERS > 0, "MAX_PLAYERS must be at least 1" print("players:", MAX_PLAYERS)hello.mojo:5:11: warning: unreachable code after compile-time assertion failure print("players:", MAX_PLAYERS) ^hello.mojo:3:5: error: function instantiation faileddef main(): ^hello.mojo:4:5: note: constraint failed: MAX_PLAYERS must be at least 1 comptime assert MAX_PLAYERS > 0, "MAX_PLAYERS must be at least 1" ^mojo: error: failed to run the pass managerYour message shows up on the constraint failed: line. This check can never be switched off, and it costs nothing at run time. You’ll use it more in Mojo Compile-Time Code; the Mojo manual’s page on constraints has the details.
Practice
Section titled “Practice”1. Guard a discount
Section titled “1. Guard a discount”Write apply_discount(price: Int, percent: Int) -> Int that returns price - price * percent // 100, with a debug_assert that percent is between 0 and 100. Call it with (200, 25) and (200, 150) and print both. Run it normally, then with -D ASSERT=all.
Hint: without -D ASSERT=all, you should see a negative price.
Show solution
def apply_discount(price: Int, percent: Int) -> Int: debug_assert(percent >= 0 and percent <= 100, "bad percent: ", percent) return price - price * percent // 100
def main(): print(apply_discount(200, 25)) print(apply_discount(200, 150))Output:
150-100With mojo run -D ASSERT=all, the second call stops with Assert Error: bad percent: 150 instead of printing -100.
2. Error or assert?
Section titled “2. Error or assert?”For each case, decide: raise an error, or assert? (a) A user types their age as "abc". (b) Your own sort function returns a list that isn’t sorted. (c) A config file is missing.
Hint: could a user cause it, even if your code is perfect?
Show solution
(a) Raise an error: users type all kinds of things, and you want to ask again. (b) Assert: only a bug in your code can cause it. (c) Raise an error: files go missing in correct programs too, and the caller may want to use defaults.
debug_assert(cond, message...)andassert cond, "message"check that something which should always be true really is.- Normal asserts are off by default; turn them on with
-D ASSERT=all(orwarnto keep going). assert_mode="safe"asserts run by default; the standard library uses them for things like list bounds.- A failed assert crashes the program (“execution crashed”);
trycan’t catch it. - Raise errors for things users can cause; assert for things only bugs can cause.
- Wrap expensive checks in a small function so they cost nothing when asserts are off.
comptime assertchecks at compile time and can’t be switched off.
Next up: compile-time code, how comptime lets Mojo work things out before your program runs.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”debug_assertin the standard library: every form, including the closure version andcpu_only.- Mojo compilation feature toggles: the
ASSERTlevels and how they relate to-gand-O. - Comptime constraints and assertions:
comptime assertandwhereconstraints. - Keywords reference: lists the
assertkeyword and what it does.