A module attribute is metadata or a compile-time value associated with an Elixir module. Compile-time attributes are inlined into compiled code, while registered attributes are stored in the generated binary and can be queried at runtime. section 2.3.6
Module attributes support several practical tasks:
- Define compile-time constants such as @pi for repeated calculations. section 2.3.6
- Attach module and function documentation with @moduledoc and @doc; iex and ex_doc can consume the stored metadata. section 2.3.6
- Declare callback intent with @impl, allowing the compiler to warn when a function does not match the GenServer behaviour contract. section 6.2.5
- Support typespecs and custom registered attributes that other Elixir or Erlang tools can inspect. section 2.3.6
iex(1)> defmodule Circle do
@pi 3.14159 #1
def area(r), do: r*r*@pi #2
def circumference(r), do: 2*r*@pi
end
iex(2)> Circle.area(1)
3.14159
iex(3)> Circle.circumference(1)
6.28318
A small Circle module demonstrates a compile-time @pi attribute reused by area/1 and circumference/1. section 2.3.6
iex(1)> defmodule EchoServer do
use GenServer
@impl GenServer #1
def handle_call(some_request, server_state) do
{:reply, some_request, server_state}
end
end
An EchoServer demonstrates placing @impl GenServer immediately before a callback so incorrect arity produces a compile-time warning. section 6.2.5
