Skip to content

Mojo Closures

A closure is a function, defined inside another function, that uses variables from around it. You’ll use them to hand a small piece of behavior to another function, together with the data it needs. Python has closures too, but Mojo asks you for one extra thing: a capture list that says which outer variables the closure uses, and whether it may change them.

You can define a function inside another one. It only exists inside that function, which is handy for small helpers nobody else needs:

def main():
def square(x: Int) -> Int:
return x * x
print(square(4))
print(square(9))

Output:

16
81

square only uses its own argument, x, so it needs nothing from outside. It’s a nested function, but not a closure yet.

Now let’s make the inner function use a variable from main. If you write it the way you would in Python, Mojo stops you:

def main():
var multiplier = 3
def scale(x: Int) -> Int:
return x * multiplier
print(scale(5))
hello.mojo:5:20: error: Could not infer capture convention of the captured value multiplier
return x * multiplier
^
mojo: error: failed to parse the provided Mojo source module

Mojo wants to know how scale uses multiplier: just reading it, changing it, or keeping its own copy. You say that in a capture list, in curly braces after the arguments:

def main():
var multiplier = 3
def scale(x: Int) {imm multiplier} -> Int:
return x * multiplier
print(scale(5))

Output:

15

{imm multiplier} means “this function reads multiplier and doesn’t change it”. With that, scale is a closure. The capture list goes after the arguments and before ->.

Why the extra typing? In a language that cares about speed and safety, it matters whether a closure reads a value, changes it, or holds a copy of it. Writing it down means you and the compiler always know. The Mojo manual’s page on closures explains the design.

imm (short for immutable) gives the closure a read-only view of the variable itself, not a copy. So if the variable changes later, the closure sees the new value:

def main():
var limit = 10
def is_small(x: Int) {imm limit} -> Bool:
return x < limit
print(is_small(5))
limit = 3
print(is_small(5))

Output:

True
False

The second call gives a different answer, because limit is now 3. Read-only means the closure can’t change it, though:

def main():
var total = 0
def add(x: Int) {imm total}:
total += x
add(1)
hello.mojo:5:9: error: expression must be mutable for in-place operator destination
total += x
^~~~~
mojo: error: failed to parse the provided Mojo source module

A plain name in the list, like {limit}, means the same as {imm limit}.

When a closure should update a variable outside it, capture it with mut:

def main():
var total = 0
def add(x: Int) {mut total}:
total += x
add(10)
add(20)
add(5)
print(total)

Output:

35

Each call changes the real total in main. This works for lists too. Here a closure keeps a log:

def main():
var log = List[String]()
def record(event: String) {mut log}:
log.append(event)
record("started")
record("loaded file")
record("finished")
print(log)
print(len(log), "events")

Output:

[started, loaded file, finished]
3 events

Sometimes you want the closure to remember the value as it was when the closure was created. Capture it with var, and the closure gets its own copy:

def main():
var price = 42
def frozen() {var price} -> Int:
return price
price = 999
print("closure sees:", frozen())
print("price is now:", price)

Output:

closure sees: 42
price is now: 999

The copy is made where the closure is defined, so later changes to price don’t reach it. Copying a big list takes time and memory, so use imm or mut when you don’t need an independent copy.

A capture list can name several variables, each with its own convention:

def main():
var name = "Mojo"
var count = 0
def tick() {imm name, mut count}:
count += 1
print(name, "tick", count)
tick()
tick()
print("count is", count)

Output:

Mojo tick 1
Mojo tick 2
count is 2

If you don’t want to list every name, a convention on its own sets the default for every outer variable the closure uses. {mut} captures all of them as mut, {imm} as read-only:

def main():
var a = 1
var b = 2
def total() {imm} -> Int:
return a + b
var hits = 0
def hit() {mut}:
hits += 1
hit()
hit()
print(total(), hits)

Output:

3 2

Naming each variable is clearer, and it turns an accidental use of some other variable into an error instead of a silent capture. The short forms are fine for tiny closures.

Here’s the whole set in one table:

Capture What the closure gets Changes outside visible inside? Can change the outer variable?
{imm x} or {x} A read-only reference Yes No
{mut x} A mutable reference Yes Yes
{var x} Its own copy No No (only its copy)
{var x^} The value itself, moved in Not applicable Outer x is gone
{} Nothing Not applicable Not applicable

Here’s where closures pay off. You can pass one to another function, which calls it without knowing anything about the variables it captured:

def count_matching[F: def(Int) -> Bool](values: List[Int], keep: F) -> Int:
var count = 0
for v in values:
if keep(v):
count += 1
return count
def main():
var scores: List[Int] = [55, 90, 72, 38, 81]
var pass_mark = 70
def passed(s: Int) {imm pass_mark} -> Bool:
return s >= pass_mark
print(count_matching(scores, passed))
pass_mark = 50
print(count_matching(scores, passed))

Output:

3
4

The new part is the signature of count_matching:

  • [F: def(Int) -> Bool] says: “F is any function type that takes an Int and returns a Bool”. The square brackets hold a compile-time parameter, and Mojo fills in F for you from what you pass. Parameters get their own lesson, Mojo Parameters.
  • keep: F is the argument that receives the closure. Inside, you call it like any function: keep(v).

count_matching doesn’t know what a pass mark is. The closure carries that. Change pass_mark and the same closure gives a different count, because it captured it with imm.

A closure with mut captures works the same way. Here, one pass over the list updates two counters in main:

def for_each[F: def(Int) -> None](values: List[Int], f: F):
for v in values:
f(v)
def main():
var nums: List[Int] = [3, 8, 1, 12]
var total = 0
var big = 0
def tally(x: Int) {mut total, mut big}:
total += x
if x > 5:
big += 1
for_each(nums, tally)
print("total:", total, "big:", big)

Output:

total: 24 big: 2

An ordinary top-level function with the right shape works too: count_matching(scores, some_def_function) is fine.

Mojo closures are more limited than Python’s, and it’s better to know that up front:

  • A closure can’t outlive the function that created it. You can’t return one from a function or keep it around after that function ends. The Python trick of a make_adder(n) that returns a new function doesn’t work with closures in Mojo 1.2. The closure reference lists this restriction.
  • Captures are explicit. Every outer variable needs to be covered by the capture list.
  • The manual marks closures as an evolving feature. The capture-list syntax on this page is the current one; older Mojo code you find online may use a @parameter decorator or capturing instead, which are the old way.

For short one-expression behavior, there’s also the lambda, which is next.

Python Mojo
Nested function reads outer variable Automatic {imm x} (or {x})
Nested function assigns outer variable nonlocal x {mut x}
Remember the value at creation time Default-argument trick x=x {var x}
Return a closure from a function Common (make_adder) Not supported
Take a function as an argument def f(callback): def f[F: def(Int) -> Int](callback: F):

In main, create var balance = 100. Write a closure spend(amount: Int) that subtracts amount from balance. Call it with 30 and 25, then print balance.

Hint: the closure changes an outer variable, so it needs mut.

Show solution
def main():
var balance = 100
def spend(amount: Int) {mut balance}:
balance -= amount
spend(30)
spend(25)
print("balance:", balance)

Output:

balance: 45

{mut balance} lets the closure change main’s variable, so both calls take money from the same balance.

This program doesn’t build. Fix the capture list so it prints Hello, Ana! and then Hi, Ana!.

def main():
var greeting = "Hello"
def greet(name: String):
print(greeting + ", " + name + "!")
greet("Ana")
greeting = "Hi"
greet("Ana")

Hint: the closure only reads greeting, and it should see the new value on the second call.

Show solution
def main():
var greeting = "Hello"
def greet(name: String) {imm greeting}:
print(greeting + ", " + name + "!")
greet("Ana")
greeting = "Hi"
greet("Ana")

Output:

Hello, Ana!
Hi, Ana!

imm is a read-only reference to the real variable, so the second call sees "Hi". With {var greeting} both calls would print Hello.

Write count_if[F: def(String) -> Bool](words: List[String], check: F) -> Int. In main, set var min_length = 4 and use a closure to count the words in ["fig", "banana", "kiwi", "apple"] with more than min_length bytes.

Hint: use w.byte_length() > min_length inside the closure, and capture min_length with imm.

Show solution
def count_if[F: def(String) -> Bool](words: List[String], check: F) -> Int:
var count = 0
for w in words:
if check(w):
count += 1
return count
def main():
var words: List[String] = ["fig", "banana", "kiwi", "apple"]
var min_length = 4
def is_long(w: String) {imm min_length} -> Bool:
return w.byte_length() > min_length
print(count_if(words, is_long))

Output:

2

count_if only knows how to loop and count. The closure decides what “long” means, using min_length from main.

  • A closure is a nested function that uses variables from the function around it.
  • Mojo needs a capture list in {} after the arguments; without it, using an outer variable is an error.
  • {imm x} reads the live value, {mut x} can change it, {var x} keeps its own copy.
  • {imm}, {mut} and {var} on their own set the convention for every outer variable used.
  • Pass closures to functions that take [F: def(Int) -> Bool](f: F) and call them like normal functions.
  • Closures can’t be returned or outlive the function that made them.

Next up: lambdas, tiny one-expression functions you can write right where you need them.

Quick check

1. A nested function uses the outer variable limit without a capture list. What happens?
2. Which capture lets a closure add to an outer total?
3. A closure captures {var price} while price is 42. Then price = 999. What does the closure see?
4. Which of these does Mojo 1.2 not support?