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.
Making an Optional
Section titled “Making an Optional”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:
36None99Optional(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:
BoNoneWhen there’s an answer, the function returns it. When there isn’t, it returns None. Both fit the return type Optional[String].
Checking whether there’s a value
Section titled “Checking whether there’s a value”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 valuemissing is emptymissing is Nonefound is not NonePick whichever reads best. if x: is the shortest.
Getting the value out
Section titled “Getting the value out”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 moduleYou 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: 372. 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, friendlives: 3or_else is the best choice when there’s a sensible default.
Unwrapping with if case and match
Section titled “Unwrapping with if case and match”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, Ada0 not found1 is Ada2 not foundif 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.
Where you’ll meet Optional
Section titled “Where you’ll meet Optional”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:
0Bo is at index 1Dict.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.
Turning an error into an Optional
Section titled “Turning an error into an Optional”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 -> 42abc -> not a number7 -> 7parse_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.
Coming from Python?
Section titled “Coming from Python?”| 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 |
Practice
Section titled “Practice”1. First long word
Section titled “1. First long word”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:
pythonnone foundThe function returns as soon as it finds a match. If the loop ends without one, it returns None.
2. Safe divide
Section titled “2. Safe divide”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.5NoneThe caller can’t use the result without dealing with the empty case, so dividing by zero can’t sneak through.
3. Fix the program
Section titled “3. Fix the program”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:
0or_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 aTor nothing. Make one with a value, withNone, or withOptional(value).- A plain
IntorStringcan never beNonein Mojo; that’s whatOptionalis for. - Check with
if x:,if not x:,x is Noneorx is not None. - Get the value with
.value()after a check, or with.or_else(default)..value()on an emptyOptionalstops the program. if case .Some(v) = x:andmatchwith.Some(v)/.Nonecheck and unwrap in one step.Dict.get(key)andList.try_index(x)return anOptional.
Next up: arrays, the fixed-size collection that a bare [1, 2, 3] creates.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Optional API docs: every method, including
take(),map()andand_then(). - Mojo manual: Types: the official introduction to
Optional. - Compound statements reference: how
matchandif casepatterns work. - Mojo manual: Errors: raising and catching errors, the other way to report “no result”.