Kernel.SpecialForms.import
import
, go back to Kernel.SpecialForms module for more information.
Imports functions and macros from other modules.
import/2
allows one to easily access functions or macros from
other modules without using the qualified name.
Examples
If you are using several functions from a given module, you can import those functions and reference them as local functions, for example:
iex> import List
iex> flatten([1, [2], 3])
[1, 2, 3]
Selector
By default, Elixir imports functions and macros from the given module, except the ones starting with an underscore (which are usually callbacks):
import List
A developer can filter to import only macros or functions via the only option:
import List, only: :functions
import List, only: :macros
Alternatively, Elixir allows a developer to pass pairs of
name/arities to :only
or :except
as a fine grained control
on what to import (or not):
import List, only: [flatten: 1]
import String, except: [split: 2]
Importing the same module again will erase the previous imports,
except when the except
option is used, which is always exclusive
on a previously declared import/2
. If there is no previous import,
then it applies to all functions and macros in the module. For
example:
import List, only: [flatten: 1, keyfind: 4]
import List, except: [flatten: 1]
After the two import calls above, only List.keyfind/4
will be
imported.
Underscore functions
By default functions starting with _
are not imported. If you really want
to import a function starting with _
you must explicitly include it in the
:only
selector.
import File.Stream, only: [__build__: 3]
Lexical scope
It is important to note that import/2
is lexical. This means you
can import specific macros inside specific functions:
defmodule Math do
def some_function do
# 1) Disable "if/2" from Kernel
import Kernel, except: [if: 2]
# 2) Require the new "if/2" macro from MyMacros
import MyMacros
# 3) Use the new macro
if do_something, it_works
end
end
In the example above, we imported macros from MyMacros
,
replacing the original if/2
implementation by our own
within that specific function. All other functions in that
module will still be able to use the original one.
Warnings
If you import a module and you don't use any of the imported functions or macros from this module, Elixir is going to issue a warning implying the import is not being used.
In case the import is generated automatically by a macro, Elixir won't emit any warnings though, since the import was not explicitly defined.
Both warning behaviours could be changed by explicitly
setting the :warn
option to true
or false
.
Ambiguous function/macro names
If two modules A
and B
are imported and they both contain
a foo
function with an arity of 1
, an error is only emitted
if an ambiguous call to foo/1
is actually made; that is, the
errors are emitted lazily, not eagerly.