liveBook · Manning

Module attribute

As explained in Elixir in Action, Third Edition

A module attribute is metadata or a compile-time value associated with an Elixir module.

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

How Elixir in Action, Third Edition covers it

How deep it goes
Explains compile-time inlining, runtime storage, documentation tooling, custom registration, and callback warnings without detailing compiler internals.
Examples
Uses Circle calculations, Code.fetch_docs, iex help, typespec declarations, and an incorrectly shaped EchoServer callback.
What it assumes
Assumes familiarity with Elixir modules and compilation, while demonstrating attribute usage through small runnable examples.
What you can do after
Apply it via Elixir attributes to inline constants, expose documentation, and catch GenServer callback mistakes during compilation.
How it connects
Connects module attributes with compile-time constants, module documentation, typespecs, Erlang tooling, and GenServer behaviours.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.