Lesson 34 of 55
10 mins readPython Writing Macros: macro ... end & @macroexpand
In Plain English
Macros take unevaluated expressions as inputs and return modified expressions at parse time before code is compiled. Call them with the @ prefix.
Deep Dive: How It Works
Macro Definition: macro name(arg) ... end receives arguments as Expr or Symbol objects and returns a replacement Expr.
Macro Invocation: @name expr passes the unevaluated AST of expr to the macro.
@macroexpand: A built-in tool that shows the exact code generated by a macro without running it.
Core Rules to Remember

Compile-Time Transformation: Macros execute during parsing/lowering before LLVM compilation.

@macroexpand Inspection: Debug macro outputs by inspecting their expanded code.
Live Interactive Example
Hit Run Code to see it liveWriting and Expanding a Custom Macro
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output Console
Click "Run Code" to view the rendered output.
How it works: @log_run transformed the input code into a logging block at compile time.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Define a Doubling Macro
Define `macro double_it(ex) return :( 2 * $(esc(ex)) ) end`.
Call `val = @double_it 10 + 5` and print `"Doubled: $val"`.
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.