TExcelTAD
Home › Julia › Julia Scope

Julia Scope

The scope of a variable is the region of code where its name is visible. Julia has a global scope per module and local scopes introduced by certain blocks. Knowing the rules explains when you need the global and local keywords.

Which blocks create a scope?

Construct New scope?
module ... end new global scope
function, x -> ..., do blocks local (hard) scope
for, while, try/catch, let local scope
comprehensions and generators local scope
struct local scope for field definitions
if, begin ... end no new scope

Local variables inside functions

Variables assigned inside a function are local to that function. They don't exist outside, and they don't affect globals with the same name:

julia · try it yourself
x = 100          # a global

function compute()
    x = 1        # a new local x; the global is untouched
    y = x + 1
    return y
end

println(compute())
println(x)
println(isdefined(Main, :y))
2
100
false

Functions can read globals freely. To assign a global from inside a function, declare it global:

julia · try it yourself
counter = 0

function bump!()
    global counter += 1
    return counter
end

bump!(); bump!()
println(counter)

show_counter() = println("counter is ", counter)   # reading needs no keyword
show_counter()
2
counter is 2

Nested functions see outer locals

An inner function (or a loop inside a function) shares the local variables of the enclosing function. Assigning to one of them updates it:

julia · try it yourself
function running_total(values)
    total = 0
    add(v) = (total += v)     # updates the outer local `total`
    for v in values
        add(v)
    end
    return total
end
println(running_total([5, 10, 20]))

function loop_demo()
    last_seen = 0
    for i in 1:3
        last_seen = i          # updates the function's local
    end
    return last_seen
end
println(loop_demo())
35
3

Loops at the top level: soft scope

Loops in a script create soft local scopes. If a loop body assigns to a name that already exists as a global, what happens depends on where the code runs:

  • In the REPL and notebooks, the assignment updates the global (convenient for experimenting).
  • In a file, the assignment is ambiguous: Julia prints a warning and treats the variable as a new local, which usually causes an UndefVarError.

The fix is the same everywhere: write global, or better, put the loop inside a function.

julia · try it yourself
total = 0
for i in 1:4
    global total += i
end
println(total)

function sum_squares(n)
    s = 0
    for i in 1:n
        s += i^2         # no keyword needed inside a function
    end
    s
end
println(sum_squares(4))
10
30

let blocks

let creates a new local scope with fresh bindings, useful to limit a variable's lifetime or to capture the current value of a variable in a closure:

julia · try it yourself
a = 1
result = let a = 10, b = 20
    a + b              # uses the local a
end
println(result, " ", a)

fs = Function[]
for i in 1:3
    push!(fs, () -> i * 100)   # each iteration has its own i
end
println([f() for f in fs])
30 1
[100, 200, 300]

Because each for iteration gets a fresh i, every closure remembers its own value.

The local keyword

local x forces a new local variable even if an outer one exists. It's rarely needed, but can make intent explicit:

julia · try it yourself
function shadow_demo()
    x = 1
    for i in 1:2
        local x = i * 10      # a new x for this iteration only
    end
    return x
end
println(shadow_demo())
1

Constants and performance

A non-constant global can change type at any moment, so functions that read it can't be optimised well. Mark configuration values const, or pass data as function arguments:

julia
const RATE = 0.07            # fast: the type is fixed
interest(p) = p * RATE

rate = 0.07                  # slow: any function reading `rate` must check its type

Test yourself

Does an if block introduce a new local scope?

  1. Yes
  2. No
  3. Only inside functions
  4. Only with local

What keyword lets a function assign to a global variable?

  1. local
  2. global
  3. const
  4. outer

Inside a function, a nested for loop assigns to a variable s defined earlier in the function. What happens?

  1. A new loop-local s is created
  2. The function's s is updated
  3. An error is raised
  4. A global s is created