ZetCode

Julia Macros Tutorial

last modified November 18, 2026

A macro is a function that operates on Julia code before that code is run. It takes expressions as arguments and returns a new expression, which is then inserted into the program. This is called metaprogramming: writing code that writes code. Macros are recognised by the @ prefix, as in @show or @assert.

This tutorial introduces expressions, inspects macro expansion with macroexpand, demonstrates the built-in macros @show, @assert and @time, and teaches you to write your own including a macro that respects Julia's hygiene rules. All examples were verified with Julia 1.13.4.

Expressions

Before writing a macro it helps to see what Julia code looks like as data. The colon syntax :(...) creates an Expr object instead of evaluating the code inside it.

main.jl
ex = :(a + b)
println(ex)
println(typeof(ex))
println(Meta.parse("1 + 2"))

The expression a + b is stored as an Expr, Julia's type for unevaluated code. println shows it in a readable form. The Meta.parse function turns a string of Julia source into an expression, which is how the parser itself represents what you type.

$ julia main.jl
a + b
Expr
1 + 2

The @show Macro

@show prints an expression together with its value, which is handy while debugging. It prints both to standard output and then returns the value.

main.jl
x = 5
@show x
@show x + 3

The first line prints x = 5 because the expression is simply the variable name. The second prints x + 3 = 8; the expression is kept as text while its value is computed. No println call is needed, which makes @show much quicker to type during exploration.

$ julia main.jl
x = 5
x + 3 = 8

The @assert Macro

An assertion is a check that must hold at a particular point in a program. @assert raises an error when its condition is false, and does nothing when the condition is true.

main.jl
x = 4
@assert x > 0
@assert x == 4 "x must be four"
println("all assertions passed")

Both assertions succeed, so the only visible result is the final message. The second form supplies a custom error message that is shown if the check fails. Expanding the macro shows a plain if statement that throws an AssertionError when the condition is false. Assertions document internal assumptions and catch mistakes early; they are always active, so use explicit checks with meaningful exceptions for validating user input.

$ julia main.jl
all assertions passed

The @time Macro

@time runs an expression and reports how long it took, how much memory it allocated and how much of that time was spent in garbage collection and compilation.

main.jl
@time sum(sin.(1:1000))

The first line of the report is wall-clock time, the second is the number of allocations and bytes, and later lines appear when compilation or garbage collection contributed. Timings change from run to run and from machine to machine, so no output block is shown; run the snippet yourself to see the numbers on your system. For a deterministic view of allocations, see Julia performance tips, which uses @allocated.

Inspecting Expansion with macroexpand

The macroexpand function shows the expression a macro produces, without running the final code. It is the best way to understand what a macro actually does.

main.jl
macro double(ex)
    return :(2 * $(esc(ex)))
end

println(macroexpand(Main, :(@double(21))))

The first argument to macroexpand is the module in which the expression is expanded; Main is the top-level module of a script. The result 2 * 21 is the code that will be compiled. Notice the interpolation $(esc(ex)): it inserts the caller's expression into the new one, and esc tells Julia to resolve it in the caller's scope. Hygiene and esc are explained below.

$ julia main.jl
2 * 21

Writing Your Own Macro

A macro is defined with the macro keyword. Its body receives expressions and returns another expression, usually built with :(...) and interpolation.

main.jl
macro double(ex)
    return :(2 * $(esc(ex)))
end

println(@double(21))
a = 5
println(@double(a + 1))

The macro accepts any expression, not just a number. @double(21) becomes 2 * 21 and prints 42; @double(a + 1) becomes 2 * (a + 1), so with a = 5 it prints 12. Because macro expansion happens before evaluation, the arguments are never computed before being substituted.

$ julia main.jl
42
12

Hygiene and esc

Julia macros are hygienic: variables introduced inside a macro are renamed automatically so they cannot accidentally overwrite variables in the code that calls the macro. The esc function opts out of this renaming for an expression that should refer to the caller's variables.

main.jl
macro swap(a, b)
    return :(begin
        temp = $(esc(a))
        $(esc(a)) = $(esc(b))
        $(esc(b)) = temp
    end)
end

x, y = 1, 2
temp = 999
@swap(x, y)
println("x = ", x, ", y = ", y, ", temp = ", temp)

The macro uses its own temp as scratch space. Julia renames that internal variable, so the caller's temp = 999 survives unchanged. The arguments x and y are escaped because the macro must read and write those variables in the caller's scope. Without esc, the assignment would target renamed variables and fail with an UndefVarError. This combination — hygienic locals plus escaped arguments — is the standard pattern for safe macros.

$ julia main.jl
x = 2, y = 1, temp = 999

Built-in Macros Overview

Julia's standard library contains many macros that save typing in common situations. A few of the most useful ones are listed below.

Each of these is an ordinary macro: it rewrites the code you write into other Julia expressions. The difference is only that they are predefined in Base or in a standard library such as Test and InteractiveUtils.

Best Practices for Macros

Macros are powerful, so a few constraints keep them understandable.

Source

Julia Metaprogramming documentation

Julia Functions documentation

This tutorial explained expressions, expansion with macroexpand, the built-in macros @show, @assert and @time, and how to define hygienic macros with esc. Functions, which are usually the better tool, are covered in Julia functions; macros used for performance work appear in Julia performance tips, and testing macros in Julia testing.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Julia tutorials.