Elixir alias, require, import & use
Elixir has four directives that control how you refer to other modules. They are lexically scoped: a directive inside a function or module only applies there, which keeps their effect easy to see.
| Directive | What it does | Example |
|---|---|---|
alias |
gives a module a shorter name | alias MyApp.Accounts.User → User |
import |
lets you call functions without the module prefix | import Enum, only: [map: 2] → map(list, f) |
require |
makes a module's macros available | require Logger → Logger.info("hi") |
use |
lets a module inject code into yours | use GenServer |
alias
Module names are often long and nested. alias creates a short name for one (by default its last part):
defmodule MyShop.Billing.Invoice do
def number(id), do: "INV-" <> String.pad_leading(Integer.to_string(id), 5, "0")
end
defmodule MyShop.Billing.TaxRate do
def for(:pt), do: 0.23
end
defmodule Checkout do
alias MyShop.Billing.Invoice
alias MyShop.Billing.TaxRate, as: Tax
# several at once: alias MyShop.Billing.{Invoice, TaxRate}
def summary(id, country), do: "#{Invoice.number(id)} (VAT #{Tax.for(country) * 100}%)"
end
IO.puts(Checkout.summary(42, :pt))INV-00042 (VAT 23.0%)
Module names are just atoms, so alias is pure compile-time renaming: Invoice becomes :"Elixir.MyShop.Billing.Invoice".
import
import brings a module's functions (and macros) into scope so you can call them without the prefix. Always limit what you import with only: (or except:) so readers can tell where a function comes from:
defmodule Geometry do
import :math, only: [sqrt: 1, pi: 0]
def distance({x1, y1}, {x2, y2}), do: sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def circle_area(r), do: Float.round(pi() * r * r, 2)
end
IO.inspect(Geometry.distance({0, 0}, {3, 4}))
IO.inspect(Geometry.circle_area(2))
# Directives work inside any block, even a function body
defmodule Report do
def lines(rows) do
import String, only: [pad_trailing: 2, upcase: 1]
Enum.map(rows, fn {k, v} -> pad_trailing(upcase(k), 8) <> v end)
end
end
Enum.each(Report.lines([{"name", "Ada"}, {"lang", "Elixir"}]), &IO.puts/1)5.0
12.57
NAME Ada
LANG Elixir
Every module automatically imports Kernel, which is why is_integer/1, length/1, if and def need no prefix.
require
Macros are code that runs at compile time and generates code. To use a module's public macros, the compiler must load that module first, which is what require ensures. The best-known example is Logger, whose macros skip building log messages that won't be printed:
require Integer
IO.inspect(Integer.is_even(10))
IO.inspect(Enum.filter(1..10, &Integer.is_odd/1))
classify = fn
n when Integer.is_even(n) -> "even"
_ -> "odd"
end
IO.puts(classify.(7))true
[1, 3, 5, 7, 9]
odd
Integer.is_even/1 is a macro (usable in guards, as shown), so require Integer is needed. Forgetting require gives a compile error that tells you to add it. (import also requires the module automatically.)
use
use SomeModule calls the SomeModule.__using__/1 macro, which injects code into your module: function definitions, @behaviour declarations, imports. It is how frameworks add functionality with one line:
defmodule Greeting do
defmacro __using__(opts) do
word = Keyword.get(opts, :word, "Hello")
quote do
def greet(name), do: "#{unquote(word)}, #{name}!"
end
end
end
defmodule English do
use Greeting
end
defmodule Spanish do
use Greeting, word: "Hola"
end
IO.puts(English.greet("Sam"))
IO.puts(Spanish.greet("Sam"))Hello, Sam!
Hola, Sam!
quote returns the code inside it as data, and unquote inserts a value into that code. This is metaprogramming; you don't need to write macros often, but knowing that use is "run this macro, which adds code" removes the mystery from use GenServer, use Phoenix.Controller and use ExUnit.Case.
Choosing the right directive
- Use alias freely: it only shortens names.
- Use import sparingly and with
only:. It is common in tests (import ExUnit.CaptureIO) and DSL-heavy code. - require only when you call a module's macros.
- use when a library documents it; read its docs to know what it injects.
Test yourself
After alias MyApp.Accounts.User, how do you refer to the module?
Accounts.UserUserMyApp.User:user
Why do you need require Logger before Logger.info/1?
- Logger is a private module
Logger.infois a macro, and macros need the module to be required- To start the Logger application
- It is optional style
What does use GenServer actually do?
- Imports all GenServer functions
- Calls
GenServer.__using__/1, which injects code into your module - Starts a GenServer
- Creates an alias