Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 40 ยท Modules and Packages

Modules and Scope

Organize Julia code with modules, learn the difference between using and import, export names, and master global and local scope, let blocks and closures.

Two ideas keep large programs manageable: namespaces, which stop names from colliding, and scope, which decides where a variable can be seen. In Julia the first is handled by modules and the second by a small set of rules about which blocks create new variables. Both are easy to get slightly wrong, and the errors can be confusing, so this lesson gives you the whole picture in one place.

You will learn how to create a module, how using differs from import, how export works, what is global and what is local, how let blocks and closures behave, and the "soft scope" rule that trips up people moving code from the REPL into a script. The Julia code is read-only on this site; the Python stand-ins illustrate namespaces and closures with Python's own rules, and the lesson points out where the two languages differ.

Modules are namespaces

A module block creates a separate global scope with its own names:

JULIA
module Geometry

export area, Circle

struct Circle
    r::Float64
end

area(c::Circle) = pi * c.r^2
helper(x) = 2x            # not exported

end # module

Every file you run starts in a module called Main, and the REPL does too. Names defined inside Geometry do not leak into Main unless you ask. To use them from the same file, refer to the module with a dot, because it is defined in the current scope rather than loaded from a package:

JULIA
using .Geometry
area(Circle(2.0))        # 12.566370614359172
Geometry.helper(21)      # 42, reachable by qualifying the name
helper(21)               # ERROR: UndefVarError: `helper` not defined

The leading dot in using .Geometry means "a module in the current module"; without it Julia looks for an installed package called Geometry. Inside a module that lives in another module, use .. to climb one level.

Bringing names in

using M Gets M's exported names, plus M.name.
using M: f, g Gets only f and g.
import M Only M.name. Nothing else comes in.

Exports only affect using, never import.

1 / 2

using versus import

Both bring a module's contents into your scope, with different guarantees:

JULIA
using .Geometry              # exported names (area, Circle) + Geometry.name
using .Geometry: area        # only area
import .Geometry             # only the qualified form: Geometry.area
import .Geometry: area       # area as a short name, and you may extend it
import .Geometry: helper as h   # rename on the way in (Julia 1.6+)

export is a promise about the module's public API, and it only matters for using. It lists the names that using M pulls in without qualification. Be conservative: exporting too many names risks collisions in the user's scope. If two modules export the same name and you use both, Julia warns and the ambiguous name becomes unusable until you qualify it.

The practical rules:

  • Use using for convenient access to a package's main API.
  • Use import (or Base.name) when you intend to add methods to a function, as in Interfaces and Iteration Protocols.
  • Qualified access, Geometry.area, always works and documents where a name comes from.
  • Since Julia 1.11, the public keyword marks names as part of the API without exporting them.

Global and local scope

A variable is global if it is defined at the top level of a module and local if it is defined inside a scope-creating block. The blocks that create a local scope are functions, for and while loops, try/catch, let and comprehensions. The blocks if, begin and quote do not create a scope.

JULIA
x = 10                     # global to Main

function f()
    y = x + 1              # x is read from the global scope; y is local
    return y
end

f()                        # 11

for i in 1:3
    z = i * 2              # z is local to the loop body
end
z                          # ERROR: UndefVarError: `z` not defined

To assign to a global from inside a function, declare it with global:

JULIA
counter = 0
function bump!()
    global counter += 1
end
bump!(); bump!()
counter                    # 2

Heavy use of mutable global variables is a bad habit in Julia: the compiler cannot know their types, which makes code slow. Pass values as arguments, or mark constants with const. The performance chapter shows the cost.

Soft scope: the REPL versus a script

There is one famous inconsistency, and it exists for a good reason. Consider:

JULIA
s = 0
for i in 1:3
    s += i
end
println(s)

In the REPL (and notebooks) this prints 6: for convenience, assigning to an existing global inside a top-level loop updates that global. In a script file run with julia file.jl, the same code does not update the global. Julia treats s as a new local variable, warns that the assignment "is ambiguous because a global variable by the same name exists", and then fails with UndefVarError: s not defined in local scope, because s += i reads the local before it has a value.

Fix it in one of two ways:

JULIA
# Option 1: say what you mean
s = 0
for i in 1:3
    global s += i
end

# Option 2 (better): put it in a function, where locals are normal
function total(n)
    s = 0
    for i in 1:n
        s += i
    end
    return s
end

Inside a function there is no ambiguity: assigning to a name that exists in an enclosing function scope updates it; otherwise a new local is created. The rule only gets confusing at the top level.

let blocks and closures

let creates a fresh local scope and can introduce bindings. It is the tool for temporarily shadowing a name or for capturing the current value of a variable:

JULIA
x = 5
let x = 100, y = 2
    println(x + y)         # 102
end
println(x)                 # 5, unchanged

A closure is a function that remembers variables from the scope where it was created. The classic example is a counter:

JULIA
function make_counter()
    count = 0
    return function ()
        count += 1
        return count
    end
end

next1 = make_counter()
next2 = make_counter()
next1(); next1()           # 2 on the second call
next2()                    # 1, an independent counter

Each call to make_counter creates a separate count, and the returned function updates it. Note the difference from the global case above: no global keyword is needed because count is a local of an enclosing function. One pitfall is a closure that captures a variable assigned more than once: Julia stores a "box" for it, which can slow down the code, and use let to capture a snapshot of such a variable. A loop variable, on the other hand, is a fresh binding on each iteration, so closures created in a loop behave as you would hope:

JULIA
fs = Function[]
for i in 1:3
    push!(fs, () -> i)     # each iteration has its own i
end
[f() for f in fs]          # [1, 2, 3]

Namespaces and closures in Python

Python's modules are namespaces just as Julia's are, and a closure needs nonlocal where Julia needs nothing. This stand-in uses a simple object as a module to show qualified access versus "bringing names in".

Python Qualified names and closures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that scope is a copy of the names. Julia's using does not copy values; it makes the name refer to the same binding, and the name cannot be reassigned from the outside.

The second stand-in reproduces the loop-closure behaviour and shows the snapshot trick. Python is different from Julia here: in Python all the closures share one i, while Julia gives each iteration its own.

Python Capturing loop variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last example is the closest Python gets to Julia's soft-scope error: assigning to a name makes it local to the whole function, so reading it first fails.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does using .Geometry do?

    The leading dot means the module lives in the current module rather than being a package. Exported names become available without qualification.
  2. 2. Which form lets you extend Geometry.area with a new method using the short name area?

    import allows adding methods to the imported function. using only reads the name.
  3. 3. Which block does NOT create a new local scope?

    if and begin blocks share the surrounding scope. Functions, loops, let and try each create a new local scope.
  4. 4. In a script file, s = 0 followed by for i in 1:3; s += i; end at the top level will...

    Scripts use strict scope rules. Write global s += i in the loop or move the code into a function.
  5. 5. Why do mutable global variables slow Julia code down?

    Any code may rebind a non-constant global to a different type, which blocks optimizations. Pass values as arguments or declare constants.

Summary

  • A module defines a namespace; using .M loads a module from the current file, while using M loads an installed package.
  • export lists names using brings in; import brings in only the qualified name, and you need import or Base.name to add methods.
  • Functions, loops, let, try and comprehensions create local scopes; if and begin do not.
  • Use global to assign to a global from inside a function, but prefer arguments and const.
  • In scripts, assigning to a global inside a top-level loop needs global, whereas the REPL is forgiving; functions avoid the issue.
  • let creates a fresh scope and closures capture the variables of the scope that built them.

Next, manage external code and reproducible setups in Packages and Environments.