Optional function argument?

Hi everyone I'm wondering if it's possible to have an optional argument for functions in Mojo. So then if an argument were given, it would have a value (int for instance) otherwise, it would be None.
3 Replies
ModularBot
ModularBot6mo ago
Congrats @Arvin_David, you just advanced to level 1!
sora
sora6mo ago
There are three ways to do this: - default argument using the Optional type
fn f(a: Optional[Int] = None):
...
fn f(a: Optional[Int] = None):
...
- default argument
fn f(a: Int = default_value):
...
fn f(a: Int = default_value):
...
- overload
fn f():
f(default_value)
fn f(a: Int):
...
fn f():
f(default_value)
fn f(a: Int):
...
We don't have Python's mutable default problem, so using a Optional type is unnecessary in many cases.
Arvin_David
Arvin_David6mo ago
Thanks a lot. But how can I also check if it's none or not?
from collections.optional import Optional

def main():
test(3)

fn test(item0: Int, item1: Optional[Int] = None):
print(item1.value())
from collections.optional import Optional

def main():
test(3)

fn test(item0: Int, item1: Optional[Int] = None):
print(item1.value())
For example in the code above, I wonder why the printed value is 0. As far as I know, we cannot print None at the moment, So is mojo converting None to 0, or None was initially treated like zero? How can I check if it's originally None or not? I found the solution. It's a little bit tricky but cool to know:
from collections.optional import Optional

def main():
test(3) # does not print anything
test(3, 0) # prints 0
test(3, 5) # prints 5

fn test(item0: Int, item1: Optional[Int] = None):
if item1:
print(item1.value())
from collections.optional import Optional

def main():
test(3) # does not print anything
test(3, 0) # prints 0
test(3, 5) # prints 5

fn test(item0: Int, item1: Optional[Int] = None):
if item1:
print(item1.value())
Want results from more Discord servers?
Add your server