Skip to content

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.

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 old
Bo is 25 years old

Swap 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.

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:

9
27
1024

power(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 ordering
def power(exp: Int = 2, base: Int) -> Int:
^ ~~~
mojo: error: failed to parse the provided Mojo source module

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 Unknown
Bo is 25 and lives in Oslo
Cy is 40 and lives in Unknown

The 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 here
def greet(name: String, greeting: String = "Hello"):
^
mojo: error: failed to parse the provided Mojo source module

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:

6
10
0

Inside 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.0
1.5
0.0

average(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.

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, Cy
Ana and Bo

Without 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:

12
20

This 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 here
def area(*, width: Int, height: Int) -> Int:
^
mojo: error: failed to parse the provided Mojo source module

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:

10
0
7

clamp(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.

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.5
bread costs 2.25
2 items

Leave 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.

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]) or add_one(5) fails with “value passed to mutable argument must be mutable”.
  • A mut argument 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:

3
2
1
start is still 3

mut, var and the other conventions get a full lesson in Mojo Argument Conventions, and the ownership page of the manual explains what happens underneath.

When you mix all of these in one function, they have to appear in this order:

  1. Required positional arguments
  2. Optional positional arguments (with defaults)
  3. *args
  4. Required keyword-only arguments
  5. Optional keyword-only arguments
  6. **kwargs

Plus / and * markers where you need them. In practice most functions use only one or two of these at a time.

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

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.

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
-2

Starting 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.

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:

42

Now 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: Int takes any number of values of one type; loop over it or use len() and [i].
  • Arguments after *args or a lone * are keyword-only; arguments before / are positional-only.
  • var **kwargs: Type collects extra keyword arguments into a dictionary (it must be var).
  • Use mut for an argument the function should change, var for a local copy it can change.

Next up: return values, including how to give back more than one value at once.

Quick check

1. Which signature builds?
2. Given def show(*names: String, sep: String = ", "), how do you change sep?
3. What does def area(*, width: Int, height: Int) mean?
4. You have var xs: List[Int] = [1, 2, 3] and a function def total(*values: Int). What happens with total(*xs)?