import, alias, require, use in Elixir
In Elixir, four directives change what a module can write without a prefix: import brings functions into scope, alias shortens a module name, require loads a module whose macros the code calls, and use runs a macro that injects code. They are not interchangeable, and the name of each one says what it does: import is about names, the other three are about modules.
import brings functions in
import copies the named functions of a module into the current scope, so they are called without the module prefix. The only: option keeps the list short, and except: does the opposite. Every function outside the list still needs its module:
import.exs
defmodule Greeter do import String, only: [upcase: 1] def shout(name), do: upcase(name) end IO.puts(Greeter.shout("ada"))
elixir import.exs
ADA
Inside Greeter, upcase/1 means String.upcase/1; String.trim/1 is still written in full. A broad import String also brings length/1 and at/2 into scope, where they can shadow a local function of the same name and hide which module a call belongs to. That is the import that surprises a reader, and the reason a course shows only: from the first example.
alias shortens a name
alias gives a module a shorter name in the current scope without importing any function. The short name still shows that a module is involved, which is why it reads better than an import of the same function:
alias.exs
defmodule Store do defmodule Item do def price, do: 99 end end defmodule Checkout do alias Store.Item, as: I def total(count), do: I.price() * count end IO.puts(Checkout.total(3))
elixir alias.exs
297
Without as:, alias Store.Item defines the name Item, the last segment of the path, which is the usual form. An alias is local to the module or the file that declares it and ends with it; the full name is unchanged everywhere else.
require loads a macro
A macro runs while the code is compiled, so the compiler has to load the module that defines it before it can expand the call. require does that loading, and it is needed only for macros, not for ordinary functions:
require.exs
defmodule Checker do require Integer def even?(n), do: Integer.is_even(n) end IO.puts(Checker.even?(4)) IO.puts(Checker.even?(5))
elixir require.exs
true
false
Integer.is_even/1 is a macro, which is why it works in a guard and why the require is there. Without it the call compiles as a function call and fails at run time with a message that names the macro and asks for the require. A function of a module never needs one, because the compiler only needs the module at the moment of the call.
use injects code
use Hello calls the macro Hello.__using__/1 with the options given, and whatever that macro returns is compiled into the calling module. It is require plus a hook, and libraries use it to add a whole set of functions and defaults in one line:
use.exs
defmodule Hello do defmacro __using__(_opts) do quote do def hello, do: "hello" end end end defmodule Greeter do use Hello end IO.puts(Greeter.hello())
elixir use.exs
hello
The quote block is the code that will be inserted; the def hello inside it belongs to Greeter, not to Hello. This is how use GenServer gives a module the callbacks and defaults of a server, and why a reader should look at the __using__/1 of a module when its functions seem to appear from nowhere. The behaviours lesson comes back to that case.
The mistake: an import that is too narrow
The only: list is a promise about which functions the module may call without a prefix. A name left out of the list is not imported, and the call fails at compile time with a message that names the missing function:
badimport.exs
defmodule Greeter do import String, only: [upcase: 2] def shout(name), do: upcase(name) end IO.puts(Greeter.shout("ada"))
elixir badimport.exs
error: undefined function upcase/1 (expected Greeter to define such a function or for it to be imported, but none are available)
│
4 │ def shout(name), do: upcase(name)
│ ^^^^^^
│
└─ badimport.exs:4:24: Greeter.shout/1
** (CompileError) badimport.exs: cannot compile module Greeter (errors have been logged)
The list says upcase: 2, the body calls upcase/1, and the arity is part of the name. The compiler stops before the module exists. The fix is the right arity in the list, or the full name String.upcase/1 in the body; the error is one of the clearest in the language, because it says both possible sources of the name.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
import String, only: [upcase: 1]do?Answer
It lets the module call upcase/1 without the String prefix
import brings the listed names into scope; only:/1 keeps the list small.
-
What does
alias Store.Itemadd to the current module?Answer
The short name Item for the module Store.Item
An alias is a name for a module, not an import of its functions.
-
Why does a macro need
requirebefore it is called?Answer
The compiler must load the defining module before it can expand the macro
Macros are expanded during compilation, so their module has to be required first.
-
What does
use Hellodo?Answer
It calls Hello.__using__/1 and compiles the code that macro returns
use is require plus the __using__ hook, which injects code into the caller.
-
What does this program print?
defmodule Greeter do import String, only: [upcase: 1] def shout(name), do: upcase(name) end IO.puts(Greeter.shout("ada"))Answer
ADA
The import makes upcase/1 available, and IO.puts/1 prints the result.
-
What does this program print?
defmodule Store do defmodule Item do def price, do: 99 end end defmodule Checkout do alias Store.Item, as: I def total(count), do: I.price() * count end IO.puts(Checkout.total(3))Answer
297
The alias reaches the nested module, and 99 times 3 is 297.
-
What does this program print?
defmodule Checker do require Integer def even?(n), do: Integer.is_even(n) end IO.puts(Checker.even?(4))Answer
true
The require loads the macro, and 4 is even.
-
What does this program print?
defmodule Hello do defmacro __using__(_opts) do quote do def hello, do: "hello" end end end defmodule Greeter do use Hello end IO.puts(Greeter.hello())Answer
hello
use injects the hello/0 function into Greeter, and the call prints its value.
-
What does this program print?
import Enum, only: [map: 2] IO.inspect(map([1, 2], &(&1 * 2)))Answer
[2, 4]
The imported map/2 doubles each element, and inspect shows the list.
-
What does this program do?
defmodule Greeter do import String, only: [upcase: 2] def shout(name), do: upcase(name) end IO.puts(Greeter.shout("ada"))Answer
error: undefined function upcase/1 (expected Greeter to define such a function or for it to be imported, but none are available)
The list imports upcase/2 and the body calls upcase/1, so the compiler stops.
Article author: Arthur Isaev