Mojo Function Arguments
In the last lesson every argument was required and passed in order. That’s fine for small functions, but it gets awkward fast. Mojo gives you the same tools Python does to make calls easier to read: default values, keyword arguments, and functions that take any number of values. Each one still needs a type, and that’s the main thing to watch for.
Positional arguments
Section titled “Positional arguments”The plain way to pass arguments is by position. The first value goes to the first argument, the second to the second, and so on:
def introduce(name: String, age: Int): print(name, "is", age, "years old")
def main(): introduce("Ana", 30) introduce("Bo", 25)Output:
Ana is 30 years oldBo is 25 years oldSwap the two values (introduce(30, "Ana")) and Mojo refuses to build it, because 30 can’t be a String. Types catch a lot of argument mix-ups for you. They can’t catch two arguments of the same type passed in the wrong order, though. That’s where keyword arguments help.
Default values
Section titled “Default values”Give an argument a default value with = value, and callers can leave it out:
def power(base: Int, exp: Int = 2) -> Int: return base**exp
def main(): print(power(3)) print(power(3, 3)) print(power(2, 10))Output:
9271024power(3) uses the default exp = 2. power(3, 3) passes its own value, which replaces the default.
Arguments with defaults have to come after the ones without. Otherwise Mojo couldn’t tell which value goes where:
def power(exp: Int = 2, base: Int) -> Int: return base**exp
def main(): print(power(3))hello.mojo:1:25: error: required positional argument follows optional positional argument; change the orderingdef power(exp: Int = 2, base: Int) -> Int: ^ ~~~mojo: error: failed to parse the provided Mojo source moduleKeyword arguments
Section titled “Keyword arguments”You can also pass an argument by its name, with name=value. Keyword arguments can come in any order:
def describe(name: String, age: Int, city: String = "Unknown"): print(name, "is", age, "and lives in", city)
def main(): describe("Ana", 30) describe("Bo", city="Oslo", age=25) describe(age=40, name="Cy")Output:
Ana is 30 and lives in UnknownBo is 25 and lives in OsloCy is 40 and lives in UnknownThe second call mixes both styles: "Bo" goes to name by position, and the rest are matched by name. This is handy when a function has several arguments with defaults and you only want to change one of them.
Two rules, the same as in Python:
- Positional arguments come first.
describe(name="Ana", 30)fails with “positional argument must not follow a keyword argument”. - The name has to match exactly. A typo is caught when you build:
def greet(name: String, greeting: String = "Hello"): print(greeting + ",", name)
def main(): greet("Ana", greting="Hi")hello.mojo:5:26: error: invalid call to 'greet': unexpected keyword argument 'greting' greet("Ana", greting="Hi") ~~~~~ ^~~~hello.mojo:1:5: note: function declared heredef greet(name: String, greeting: String = "Hello"): ^mojo: error: failed to parse the provided Mojo source moduleAny number of arguments: *args
Section titled “Any number of arguments: *args”Put a * in front of an argument name and the function accepts any number of values for it. This is called a variadic argument. All the values must have the type you give:
def total(*values: Int) -> Int: var sum = 0 for v in values: sum += v return sum
def main(): print(total(1, 2, 3)) print(total(10)) print(total())Output:
6100Inside the function, values acts like a read-only list. You can loop over it with for, ask for its length with len(values), and read items with values[i]:
def average(*values: Float64) -> Float64: if len(values) == 0: return 0.0 var sum = 0.0 for v in values: sum += v return sum / Float64(len(values))
def main(): print(average(2.0, 4.0, 9.0)) print(average(1, 2)) print(average())Output:
5.01.50.0average(1, 2) works because the literals 1 and 2 turn into Float64 values automatically.
The values in *values must all be the same type. Mojo can also take a mix of types, but that needs generics, which come later in Mojo Generics.
Keyword-only arguments
Section titled “Keyword-only arguments”Anything that comes after a *args argument can only be passed by keyword. That’s how you add options to a variadic function:
def show(*names: String, sep: String = ", "): var line = String() for i in range(len(names)): if i > 0: line += sep line += names[i] print(line)
def main(): show("Ana", "Bo", "Cy") show("Ana", "Bo", sep=" and ")Output:
Ana, Bo, CyAna and BoWithout a keyword, Mojo would treat " and " as just another name.
You can make arguments keyword-only in a normal function too. Put a lone * in the list, and everything after it must be passed by name:
def area(*, width: Int, height: Int) -> Int: return width * height
def main(): print(area(width=3, height=4)) print(area(height=2, width=10))Output:
1220This is useful when two arguments have the same type and are easy to swap. Calling area(3, 4) doesn’t work:
def area(*, width: Int, height: Int) -> Int: return width * height
def main(): print(area(3, 4))hello.mojo:5:15: error: invalid call to 'area': missing required argument: 'width' print(area(3, 4)) ~~~~^hello.mojo:1:5: note: function declared heredef area(*, width: Int, height: Int) -> Int: ^mojo: error: failed to parse the provided Mojo source modulePositional-only arguments
Section titled “Positional-only arguments”The opposite also exists. Arguments before a / can only be passed by position, never by name:
def clamp(value: Int, /, low: Int, high: Int) -> Int: if value < low: return low if value > high: return high return value
def main(): print(clamp(15, 0, 10)) print(clamp(-3, low=0, high=10)) print(clamp(7, 0, 10))Output:
1007clamp(value=15, low=0, high=10) would fail with missing required argument: 'value'. You’ll see / most often in the standard library, on functions where the argument name doesn’t tell the caller anything useful. It also leaves the author free to rename those arguments later.
Any number of keyword arguments: **kwargs
Section titled “Any number of keyword arguments: **kwargs”Two stars collect any number of keyword arguments. Inside the function they arrive as a dictionary of names and values. Mojo requires var in front of **kwargs (the function gets its own copy of that dictionary):
def print_prices(var **prices: Float64): for item in prices.items(): print(item.key, "costs", item.value) print(len(prices), "items")
def main(): print_prices(apple=0.5, bread=2.25)Output:
apple costs 0.5bread costs 2.252 itemsLeave out the var and the error tells you to add it: “variadic keyword arguments only support the ‘var’ convention”. All the values must share one type (here Float64), and you can’t spread an existing dictionary into a call with **d yet. The Mojo manual’s section on function arguments lists these limits.
Changing an argument with mut
Section titled “Changing an argument with mut”As you saw in Mojo Functions, arguments are read-only by default. When a function is meant to change what you pass in, mark the argument mut:
def double_all(mut values: List[Int]): for i in range(len(values)): values[i] *= 2
def main(): var nums: List[Int] = [1, 2, 3] double_all(nums) print(nums)Output:
[2, 4, 6]Two things to know about mut arguments:
- You have to pass a variable, something that can actually change.
double_all([1, 2, 3])oradd_one(5)fails with “value passed to mutable argument must be mutable”. - A
mutargument can’t have a default value (Mojo says “‘mut’ arguments must not have defaults”).
If you only want to change an argument inside the function, as a local working copy, use var instead. The caller’s variable stays the same:
def countdown(var n: Int): while n > 0: print(n) n -= 1
def main(): var start = 3 countdown(start) print("start is still", start)Output:
321start is still 3mut, var and the other conventions get a full lesson in Mojo Argument Conventions, and the ownership page of the manual explains what happens underneath.
The order of arguments
Section titled “The order of arguments”When you mix all of these in one function, they have to appear in this order:
- Required positional arguments
- Optional positional arguments (with defaults)
*args- Required keyword-only arguments
- Optional keyword-only arguments
**kwargs
Plus / and * markers where you need them. In practice most functions use only one or two of these at a time.
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
| Defaults, keyword arguments | Yes | Yes, same syntax |
*args |
Any types | One type for all values (unless generic) |
**kwargs |
**kwargs |
var **kwargs: Type |
| Spread a list into a call | f(*xs) |
Not supported |
/ and * markers |
Yes | Yes |
Practice
Section titled “Practice”1. A greeting with options
Section titled “1. A greeting with options”Write greet(name: String, greeting: String = "Hello", punctuation: String = "!") that prints something like Hello, Ana!. Call it three times: with just a name, with a different greeting, and with only the punctuation changed (by keyword).
Hint: to change only punctuation, pass it as punctuation="?".
Show solution
def greet(name: String, greeting: String = "Hello", punctuation: String = "!"): print(greeting + ", " + name + punctuation)
def main(): greet("Ana") greet("Bo", "Welcome") greet("Cy", punctuation="?")Output:
Hello, Ana!Welcome, Bo!Hello, Cy?The keyword lets you skip greeting and change only punctuation. By position you’d have to repeat "Hello" to get to the third argument.
2. Largest of many
Section titled “2. Largest of many”Write largest(*values: Int) -> Int that returns the biggest value it’s given. Print largest(4, 17, 9) and largest(-5, -2).
Hint: start with values[0], then loop and keep the bigger one.
Show solution
def largest(*values: Int) -> Int: var best = values[0] for v in values: if v > best: best = v return best
def main(): print(largest(4, 17, 9)) print(largest(-5, -2))Output:
17-2Starting with values[0] instead of 0 matters for the second call: every value is negative, so 0 would win and give the wrong answer. Calling largest() with no values would crash at values[0], so a real version should check len(values) first.
3. Safe rectangles
Section titled “3. Safe rectangles”Write rect_area(*, width: Int, height: Int) -> Int so callers must name both values. Print the area of a 6 by 7 rectangle.
Hint: a lone * at the start of the argument list makes everything after it keyword-only.
Show solution
def rect_area(*, width: Int, height: Int) -> Int: return width * height
def main(): print(rect_area(width=6, height=7))Output:
42Now rect_area(6, 7) doesn’t build, so nobody can mix up width and height by accident.
- Default values (
exp: Int = 2) make arguments optional; they go after the required ones. - Keyword arguments (
city="Oslo") can be passed in any order, after the positional ones. *values: Inttakes any number of values of one type; loop over it or uselen()and[i].- Arguments after
*argsor a lone*are keyword-only; arguments before/are positional-only. var **kwargs: Typecollects extra keyword arguments into a dictionary (it must bevar).- Use
mutfor an argument the function should change,varfor a local copy it can change.
Next up: return values, including how to give back more than one value at once.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Function arguments (Mojo manual): defaults, keywords, variadic and keyword-only arguments.
- Function declarations reference: the full grammar of argument lists, including markers and variadics.
- Ownership and argument conventions: what
mut,varand the default convention really do. - VariadicList (std docs): the type you get inside a function for
*args.