Module Attributes In Elixir


Elixir module attributes could be used as constants, or they have a particular purpose and could be accessed during the runtime. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.

Attribute as constant

Let’s add our Basketball.trials function:

You can see that number 180 is used on lines 6 and 12, and this is our first candidate for module attribute.

We can try it in iex:

Registered Attributes

Elixir has predefined attributes that are registered in the Elixir binary (compiled) beam file and could be used in runtime. What differs a great programmer from a mediocre one is how they document their work. Elixir module attributes are here to help you with documentation. Let’s explore @moduledoc and @doc module attributes.

To use it in iex (runtime), we first need to compile it. Run elixirc in the folder where is your source code:

Using iex h function, you get values for @moduldoc and @doc attributes in runtime. ex_doc is an elixir tool that, based on those two attributes, generates your project documentation.

As Elixir is a dynamic language, type mismatch could not be detected in compile time. Elixir has @spec a module attribute that we use to define a function input/output parameter types. Why? There is a tool dialyzer that is a static analysis tool, and it could detect type usage errors using @spec tags.

Our position and trials function have the same @spec because they both have for input integer, and output is Elixir String struct (this is why we do not write just string()).


  • @ is used for module attributes
  • how to document a module
  • how to document a function
  • ex_doc tool generates HTML documentation
  • how to specify function input/output types
  • how to use module attribute as constant
  • dialyzer is a static analysis tool that uses @spec attribute.

Originally published at on June 23, 2020.

Written by

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store