Skip to content

Mojo Optional

Sometimes a value might not be there: a search that finds nothing, a dictionary key that’s missing, a user who didn’t fill in a field. In Python you’d return None and hope the caller remembers to check. In Mojo, an Int is always a real number and can never be None. When “maybe nothing” is a real answer, you use Optional, a box that either holds a value or is empty. The type makes the “maybe” visible, so you can’t forget to check.

Optional[Int] means “an Int, or nothing”. You give it a value, or None:

def main():
var age: Optional[Int] = 36
var nickname: Optional[String] = None
var score = Optional(99)
print(age)
print(nickname)
print(score)

Output:

36
None
99

Optional(99) works out the type (Optional[Int]) from the value. Printing an Optional shows the value inside, or None when it’s empty. There’s no import to write; Optional is always available.

You’ll mostly meet Optional as the return type of a function that might not have an answer:

def find_user(id: Int) -> Optional[String]:
if id == 1:
return String("Ada")
if id == 2:
return String("Bo")
return None
def main():
print(find_user(2))
print(find_user(7))

Output:

Bo
None

When there’s an answer, the function returns it. When there isn’t, it returns None. Both fit the return type Optional[String].

An Optional is True in an if when it holds a value and False when it’s empty. You can also compare it with None using is and is not, like in Python:

def main():
var found: Optional[Int] = 42
var missing: Optional[Int] = None
if found:
print("found has a value")
if not missing:
print("missing is empty")
if missing is None:
print("missing is None")
if found is not None:
print("found is not None")

Output:

found has a value
missing is empty
missing is None
found is not None

Pick whichever reads best. if x: is the shortest.

An Optional[Int] isn’t an Int, so you can’t do math with it directly:

def main():
var age: Optional[Int] = 36
print(age + 1)
optional.mojo:3:15: error: 'Optional[Int]' does not implement the '__add__' method
print(age + 1)
~~~ ^
mojo: error: failed to parse the provided Mojo source module

You have to take the value out first. There are two common ways.

1. Check, then call .value(). Inside an if that checked the Optional, .value() gives you the real value:

def main():
var age: Optional[Int] = 36
if age:
print("next year:", age.value() + 1)
else:
print("age unknown")

Output:

next year: 37

2. Use .or_else(default). It gives you the value, or the default if the Optional is empty. No if needed:

def main():
var nickname: Optional[String] = None
var lives: Optional[Int] = 3
print("Hello,", nickname.or_else("friend"))
print("lives:", lives.or_else(0))

Output:

Hello, friend
lives: 3

or_else is the best choice when there’s a sensible default.

Mojo can also check and unwrap in one step, using a pattern. An Optional is either .Some(value) or .None:

def find_user(id: Int) -> Optional[String]:
if id == 1:
return String("Ada")
return None
def main():
if case .Some(name) = find_user(1):
print("Hello,", name)
for id in range(3):
match find_user(id):
case .Some(name):
print(id, "is", name)
case .None:
print(id, "not found")

Output:

Hello, Ada
0 not found
1 is Ada
2 not found

if case .Some(name) = ... runs its block only when there’s a value, and puts that value in name. The match version handles both cases, which is nice when you have something to do for the empty case too. If match is new to you, see Mojo Match. The Optional API docs use this pattern in their examples too.

The standard library returns an Optional wherever an answer might be missing. Two you’ve seen already:

def main():
var stock = {"apples": 12}
var kiwis = stock.get("kiwis")
print(kiwis.or_else(0))
var names: List[String] = ["Ada", "Bo", "Cy"]
var pos = names.try_index("Bo")
if pos:
print("Bo is at index", pos.value())

Output:

0
Bo is at index 1

Dict.get(key) returns an Optional of the value, and List.try_index(x) returns an Optional[Int] with the position. In both cases, “nothing found” is a normal result, not an error.

Some operations raise an error when they fail, like Int("abc"). If a failure is normal for your program (users type bad input all the time), a small helper can turn the error into an empty Optional:

def parse_int(text: String) -> Optional[Int]:
try:
return Int(text)
except:
return None
def main():
var inputs: List[String] = ["42", "abc", "7"]
for s in inputs:
var n = parse_int(s)
if n:
print(s, "->", n.value())
else:
print(s, "-> not a number")

Output:

42 -> 42
abc -> not a number
7 -> 7

parse_int doesn’t raise, so callers don’t need try. They just check the Optional. Errors and try get their own lessons later; the Mojo manual’s page on errors has the details.

Python Mojo
“Maybe a value” Any variable can be None Only an Optional[T] can be empty
Type hint int | None Optional[Int]
Check if x is not None: if x: or if x is not None:
Use the value Just use x x.value() after a check, or x.or_else(default)
Forget to check Error later, at run time Optional[Int] + 1 doesn’t compile

Write first_long(words: List[String]) -> Optional[String] that returns the first word longer than 4 bytes, or None. Try it on ["hi", "mojo", "python"] and on ["a", "b"], printing none found for an empty result.

Hint: use w.byte_length() > 4, and or_else("none found") when printing.

Show solution
def first_long(words: List[String]) -> Optional[String]:
for w in words:
if w.byte_length() > 4:
return w
return None
def main():
print(first_long(["hi", "mojo", "python"]).or_else("none found"))
print(first_long(["a", "b"]).or_else("none found"))

Output:

python
none found

The function returns as soon as it finds a match. If the loop ends without one, it returns None.

Write safe_divide(a: Float64, b: Float64) -> Optional[Float64] that returns None when b is 0. Print the results of safe_divide(10, 4) and safe_divide(1, 0), using if case .Some(...) for the first one.

Hint: an empty result can just be printed; it shows None.

Show solution
def safe_divide(a: Float64, b: Float64) -> Optional[Float64]:
if b == 0:
return None
return a / b
def main():
if case .Some(result) = safe_divide(10, 4):
print("10 / 4 =", result)
print(safe_divide(1, 0))

Output:

10 / 4 = 2.5
None

The caller can’t use the result without dealing with the empty case, so dividing by zero can’t sneak through.

This program crashes when the key isn’t there. Change it so it prints 0 for a missing fruit instead.

def main():
var stock = {"apples": 12}
var pears = stock.get("pears")
print(pears.value())

Hint: don’t call .value() without checking.

Show solution
def main():
var stock = {"apples": 12}
var pears = stock.get("pears")
print(pears.or_else(0))

Output:

0

or_else(0) gives the value when it’s there and 0 when it isn’t, so there’s nothing to crash on. stock.get("pears", 0) would also work.

  • Optional[T] holds either a T or nothing. Make one with a value, with None, or with Optional(value).
  • A plain Int or String can never be None in Mojo; that’s what Optional is for.
  • Check with if x:, if not x:, x is None or x is not None.
  • Get the value with .value() after a check, or with .or_else(default). .value() on an empty Optional stops the program.
  • if case .Some(v) = x: and match with .Some(v) / .None check and unwrap in one step.
  • Dict.get(key) and List.try_index(x) return an Optional.

Next up: arrays, the fixed-size collection that a bare [1, 2, 3] creates.

Quick check

1. What does print(Optional[Int](None)) show?
2. You have var n: Optional[Int] = 5. Which line prints 6?
3. What happens if you call .value() on an empty Optional?
4. Which of these returns an Optional?