Module Attributes

Notes

Order Matters

A couple things to keep in mind regarding where module attributes appear in a file:

  1. You can only set a module attribute at the top level of a module, not inside of a function definition. However, you can read (access) module attributes from inside functions.

  2. When a module attribute is read inside of a function, the value of the attribute is inlined during compilation, not at runtime. That means if the same module attribute is set multiple times in a module then the value read by a function is the value of the attribute at the time the function is defined.

To illustrate the effect of a module attribute being set multiple times, paste the following contrived module into an iex session:

defmodule Namer do
  @name "nicole"

  def her_name, do: @name

  @name "mike"
  
  def his_name, do: @name
end

Notice we set the @name module attribute twice, first to "nicole" and then to "mike". Both the her_name and his_name functions read and return the value of the @name module attribute.

When the her_name function is called, the value of the @name attribute is "nicole":

iex> Namer.her_name
"nicole"

But when the his_name function is called, the value of the @name attribute is "mike":

iex> Namer.his_name
"mike"

This demonstrated that the order in which the module attributes and the functions are defined matters. You can envision the compiler inlining the values during compilation, like so:

defmodule Namer do
  @name "nicole"

  def her_name, do: "nicole"

  @name "mike"
  
  def his_name, do: "mike"
end

Access Documentation

In the video we used @moduledoc and @doc to document a module and functions, respectively. Using these well-defined module attributes, Elixir can then access the values to generate documentation. To access the documentation, use the familiar h helper in iex like so:

iex> h Servy.Handler

iex> h Servy.Handler.handle

It's not terribly exciting documentation, but you get the point. Later on we'll learn how to add examples to the documentation which makes it more useful.

Code So Far

The code for this video is in the module-attributes directory found within the video-code directory of the code bundle.