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.
Functions inside functions
Section titled “Functions inside functions”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:
1681square only uses its own argument, x, so it needs nothing from outside. It’s a nested function, but not a closure yet.
Using an outer variable
Section titled “Using an outer variable”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 moduleMojo 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.
Reading with imm
Section titled “Reading with imm”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:
TrueFalseThe 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 moduleA plain name in the list, like {limit}, means the same as {imm limit}.
Changing with mut
Section titled “Changing with mut”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:
35Each 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 eventsKeeping a copy with var
Section titled “Keeping a copy with var”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: 42price is now: 999The 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.
Several captures at once
Section titled “Several captures at once”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 1Mojo tick 2count is 2If 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 2Naming 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 |
Passing a closure to another function
Section titled “Passing a closure to another function”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:
34The new part is the signature of count_matching:
[F: def(Int) -> Bool]says: “Fis any function type that takes anIntand returns aBool”. The square brackets hold a compile-time parameter, and Mojo fills inFfor you from what you pass. Parameters get their own lesson, Mojo Parameters.keep: Fis 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: 2An ordinary top-level function with the right shape works too: count_matching(scores, some_def_function) is fine.
What closures can’t do (yet)
Section titled “What closures can’t do (yet)”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
@parameterdecorator orcapturinginstead, which are the old way.
For short one-expression behavior, there’s also the lambda, which is next.
Coming from Python?
Section titled “Coming from Python?”| 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): |
Practice
Section titled “Practice”1. A running total
Section titled “1. A running total”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.
2. Fix the closure
Section titled “2. Fix the closure”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.
3. Count words longer than a limit
Section titled “3. Count words longer than a limit”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:
2count_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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Closures (Mojo manual): the official guide, with every capture convention and more examples.
- Closure declarations reference: the exact syntax, defaults, nesting rules and restrictions.
- Functions (Mojo manual): the basics closures build on.
- Parameterization (Mojo manual): the
[F: ...]square-bracket parameters used to accept closures.