Elixir Module Attributes
Module attributes are names prefixed with @ inside a module. They serve three purposes:
- Annotations read by Elixir and tools:
@moduledoc,@doc,@spec,@impl,@behaviour,@deprecated. - Compile-time constants: values computed once when the module is compiled.
- Temporary storage during compilation (used by libraries and macros).
Constants
defmodule Pricing do
@vat_rate 0.21
@currency "EUR"
@free_shipping_over 50
def total(net) do
gross = Float.round(net * (1 + @vat_rate), 2)
shipping = if gross >= @free_shipping_over, do: 0, else: 4.95
"#{gross + shipping} #{@currency}"
end
end
IO.puts(Pricing.total(20))
IO.puts(Pricing.total(60))29.15 EUR
72.6 EUR
When the module is compiled, each @vat_rate read is replaced by its value. There is no runtime lookup.
Values are computed at compile time
The expression assigned to an attribute runs once, at compile time. That makes attributes perfect for pre-computed lookup tables, and a trap for values that should be fresh at runtime:
defmodule Roman do
@numerals [{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"},
{50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}]
@lookup Map.new(@numerals, fn {value, text} -> {text, value} end)
def to_roman(0), do: ""
def to_roman(n) do
{value, text} = Enum.find(@numerals, fn {value, _} -> value <= n end)
text <> to_roman(n - value)
end
def symbol_value(text), do: Map.fetch(@lookup, text)
end
IO.puts(Roman.to_roman(2026))
IO.puts(Roman.to_roman(1994))
IO.inspect(Roman.symbol_value("CM"))MMXXVI
MCMXCIV
{:ok, 900}
Warning:
@started_at DateTime.utc_now()stores the moment the module was compiled, not when the program started. For runtime values call the function inside a function body, or read configuration withApplication.get_env/3at runtime.
Redefining an attribute
An attribute can be set more than once. Each function sees the value that was current where the function is defined, because reading happens at compile time from top to bottom:
defmodule Levels do
@level :info
def first, do: @level
@level :debug
def second, do: @level
end
IO.inspect(Levels.first())
IO.inspect(Levels.second()):info
:debug
Documentation attributes
@moduledoc and @doc hold documentation, written in Markdown. They are stored in the compiled module and shown by h in IEx and by ExDoc. Documentation is a first-class feature in Elixir:
defmodule Temperature do
@moduledoc """
Conversions between temperature scales.
"""
@doc """
Converts degrees Celsius to Fahrenheit.
## Examples
iex> Temperature.c_to_f(100)
212.0
"""
@spec c_to_f(number()) :: float()
def c_to_f(c), do: c * 9 / 5 + 32
@doc false # hide from the docs
def internal_helper, do: :ok
endThe examples marked iex> are executable: ExUnit's doctest Temperature runs them as tests.
Accumulating attributes
Registering an attribute with accumulate: true makes each assignment add to a list instead of replacing it. Libraries use this to let you declare things one by one (routes, fields, test cases). Here a tiny "plugin registry" collects names:
defmodule Pipeline do
Module.register_attribute(__MODULE__, :step, accumulate: true)
@step :validate
@step :normalize
@step :store
def steps, do: Enum.reverse(@step)
end
IO.inspect(Pipeline.steps())[:validate, :normalize, :store]
Accumulated values are prepended, so the list comes back in reverse declaration order; Enum.reverse/1 restores the order.
Common annotations
| Attribute | Purpose |
|---|---|
@moduledoc, @doc, @typedoc |
documentation |
@spec, @type, @typep, @opaque |
typespecs (Typespecs lesson) |
@behaviour Mod |
declares that the module implements a behaviour |
@impl true |
marks a callback implementation |
@callback |
defines a behaviour's callbacks |
@deprecated "use x/1" |
compile warnings for callers |
@derive |
derive protocol implementations for a struct |
@compile |
compiler options, e.g. @compile {:inline, f: 1} |
Test yourself
When is the expression in @limit compute_limit() evaluated?
- Every time a function reads @limit
- Once, when the module is compiled
- When the application starts
- Lazily on first use
If @x 1 is followed by def a, do: @x, then @x 2 and def b, do: @x, what does a() return?
- 1
- 2
- [1, 2]
- nil
Which attribute documents a single function?
@moduledoc@doc@spec@comment