Skip to content

Mojo Scope

The scope of a variable is the part of your code where its name means something. Outside that part, the name doesn’t exist. Mojo’s rules here are stricter than Python’s: every block (the body of an if, a loop, a function) gets its own scope. Once you know that one rule, the rest of this page follows from it.

A variable you create in a function belongs to that function. Other functions can’t see it:

def make_total() -> Int:
var total = 10
return total
def main():
var x = make_total()
print(total)
hello.mojo:7:11: error: use of unknown declaration 'total'
print(total)
^~~~~
mojo: error: failed to parse the provided Mojo source module

total only exists inside make_total. To get the value out, you return it, which the code already does: x holds 10. Printing x instead of total fixes the program.

Each call also starts fresh. A local variable doesn’t remember anything from the previous call:

def visit():
var visits = 0
visits += 1
print("visits:", visits)
def main():
visit()
visit()
visit()

Output:

visits: 1
visits: 1
visits: 1

Every call creates a new visits, sets it to 0, adds one, and throws it away when the function ends. If you want a count that survives between calls, keep it in the caller and pass it in (with mut, as in Mojo Function Arguments).

An argument is a local name for the value the caller passed. It’s fine for it to have the same name as a variable somewhere else:

def show(x: Int):
print("in show:", x)
def main():
var x = 5
show(x + 1)
print("in main:", x)

Output:

in show: 6
in main: 5

The x in show and the x in main are two different names in two different scopes. They don’t affect each other.

Here’s the big difference from Python. A variable created inside an if, for or while block disappears when that block ends:

def main():
var hot = True
if hot:
var message = "Drink water"
print(message)
print(message)
hello.mojo:6:11: error: use of unknown declaration 'message'
print(message)
^~~~~~~
mojo: error: failed to parse the provided Mojo source module

In Python this works, because Python only creates a new scope for functions. In Mojo, message belongs to the if block. The Mojo manual’s page on variables calls this block-level scope.

The fix is to create the variable before the block, in the scope where you need it, and only assign it inside:

def main():
var message: String
var hot = True
if hot:
message = "Drink water"
else:
message = "Wear a coat"
print(message)

Output:

Drink water

var message: String declares the name with a type but no value yet. Both branches then give it one. Mojo checks that it really gets a value on every path. Drop the else and you get an error, because message could still be empty when you print it:

def main():
var message: String
var hot = False
if hot:
message = "Drink water"
print(message)
hello.mojo:6:10: error: use of uninitialized value 'message'
print(message)
^
hello.mojo:2:9: note: 'message' declared here
var message: String
^
mojo: error: failed to run the pass manager

The same goes for loops. The loop variable, and anything you create in the loop body, is gone after the loop:

def main():
for i in range(3):
pass
print(i)
hello.mojo:4:11: error: use of unknown declaration 'i'
print(i)
^
mojo: error: failed to parse the provided Mojo source module

Python programmers sometimes read the loop variable after a loop to see where it stopped. In Mojo, keep the value you care about in a variable declared before the loop:

def main():
var last = 0
for i in range(5):
last = i
print("last:", last)
var found = False
var words: List[String] = ["apple", "kiwi", "plum"]
for w in words:
if w == "kiwi":
found = True
print("found kiwi:", found)

Output:

last: 4
found kiwi: True

Scopes only work one way. Code inside a block can read and change variables from the blocks around it. It’s only the other direction (outer code reading inner variables) that’s blocked:

def main():
var count = 0
var i = 0
while i < 3:
var step = i * 10
count += step
i += 1
print("count:", count)

Output:

count: 30

count and i were created outside the loop, so the loop can update them and main still sees the result. step is created fresh on every pass through the loop and never escapes it.

If you write var with a name that already exists in an outer scope, you create a new variable that hides the outer one until the block ends. This is called shadowing:

def main():
var num = 1
var dig = 1
if num == 1:
print("num:", num)
var num = 2
print("num:", num)
dig = 2
print("num:", num)
print("dig:", dig)

Output:

num: 1
num: 2
num: 1
dig: 2

Inside the if, var num = 2 creates a second num. The outer one is untouched, so it’s 1 again after the block. dig = 2 has no var, so it changes the outer dig.

In the same scope, you can’t create a name twice. var x = 1 followed by var x = 2 in one block fails with “invalid redefinition of ‘x’”. Drop the second var to change the value instead.

In Python you can create a variable at the top of a file and use it everywhere. Mojo doesn’t allow that:

var counter = 0
def main():
print(counter)
hello.mojo:1:1: error: global variables are not supported; move this into a function body or use 'comptime' to declare a constant
var counter = 0
^
hello.mojo:4:11: error: use of unknown declaration 'counter'
print(counter)
^~~~~~~
mojo: error: failed to parse the provided Mojo source module

The error offers two ways out. If the value never changes, make it a constant with comptime. Constants can live at the top of the file, and every function can use them:

comptime TAX_RATE = 0.2
def price_with_tax(price: Float64) -> Float64:
return price * (1.0 + TAX_RATE)
def main():
print(price_with_tax(100.0))

Output:

120.0

If the value does change, create it in main and pass it to the functions that need it. Mojo Constants covers comptime in more detail.

You can define a function inside another function. But by default, the inner function can’t see the outer function’s variables:

def main():
var name = "Ana"
def greet():
print("Hi", name)
greet()
hello.mojo:5:21: error: Could not infer capture convention of the captured value name
print("Hi", name)
^
mojo: error: failed to parse the provided Mojo source module

This is the one place where an inner scope can’t just read an outer variable. Mojo wants you to say exactly how the inner function uses name, with a capture list like {imm name}. That’s what a closure is, and it’s the topic of Mojo Closures.

Python Mojo
Variable made inside if/for Visible after the block Gone after the block
Loop variable after the loop Still holds the last value Doesn’t exist
Global variables Allowed (global to change them) Not allowed; use comptime constants
Reuse a name in an inner block Same variable var makes a new one (shadowing)
Nested function reads outer variable Works Needs a capture list (closure)

This program doesn’t build. Fix it so it prints Result: big.

def main():
var n = 42
if n > 10:
var result = "big"
else:
var result = "small"
print("Result:", result)

Hint: result needs to exist in the scope where it’s printed.

Show solution
def main():
var n = 42
var result: String
if n > 10:
result = "big"
else:
result = "small"
print("Result:", result)

Output:

Result: big

Declaring result before the if puts it in main’s scope. The branches only assign it, so there’s no var inside them.

Given var words: List[String] = ["fig", "banana", "kiwi"], find and print the longest word with a for loop. The result has to be printed after the loop.

Hint: keep a var longest = String("") before the loop and replace it whenever you see a longer word. Compare lengths with .byte_length().

Show solution
def main():
var words: List[String] = ["fig", "banana", "kiwi"]
var longest = String("")
for w in words:
if w.byte_length() > longest.byte_length():
longest = w
print("Longest:", longest)

Output:

Longest: banana

longest is created outside the loop, so it’s still there when the loop is done. w isn’t: it only exists inside the loop.

This program uses a global variable for a fixed greeting. Make it build without changing what it prints (Welcome, Ana).

var GREETING = "Welcome"
def greet(name: String):
print(GREETING + ",", name)
def main():
greet("Ana")

Hint: the greeting never changes, so it can be a constant.

Show solution
comptime GREETING = "Welcome"
def greet(name: String):
print(GREETING + ",", name)
def main():
greet("Ana")

Output:

Welcome, Ana

comptime makes GREETING a constant, and constants are allowed at the top level of a file.

  • A variable’s scope is the block it was created in: a function, an if, a loop body.
  • Variables created inside a block are gone after it, unlike Python. Declare them before the block if you need them later.
  • Inner blocks can read and change variables from outer blocks.
  • var with an existing name in an inner block shadows it; in the same block it’s a redefinition error.
  • No global variables. Use comptime constants at the top level, or pass values as arguments.
  • A nested function needs a capture list to use outer variables.

Next up: overloading, how to give several functions the same name.

Quick check

1. A variable is created with var inside an if block. Can you use it after the block?
2. What happens with var counter = 0 at the top level of a file?
3. var total = 0 is followed by a loop containing var total = total + i. What does print(total) show after the loop?
4. Which one is allowed?