TExcelTAD
Home › Elixir › Elixir Module Attributes

Elixir Module Attributes

Module attributes are names prefixed with @ inside a module. They serve three purposes:

  1. Annotations read by Elixir and tools: @moduledoc, @doc, @spec, @impl, @behaviour, @deprecated.
  2. Compile-time constants: values computed once when the module is compiled.
  3. Temporary storage during compilation (used by libraries and macros).

Constants

elixir · try it yourself
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:

elixir · try it yourself
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 with Application.get_env/3 at 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:

elixir · try it yourself
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:

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
end

The 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:

elixir · try it yourself
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?

  1. Every time a function reads @limit
  2. Once, when the module is compiled
  3. When the application starts
  4. 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. 1
  2. 2
  3. [1, 2]
  4. nil

Which attribute documents a single function?

  1. @moduledoc
  2. @doc
  3. @spec
  4. @comment