Do you ever `import` inside a function?

From the docs on import:

Note that import is lexically scoped too. This means that we can import specific macros or functions inside function definitions:

defmodule Math do
  def some_function do
    import List, only: [duplicate: 2]
    duplicate(:ok, 10)
  end
end

In the example above, the imported List.duplicate/2 is only visible within that specific function. duplicate/2 won’t be available in any other function in that module (or any other module for that matter).

The example given is silly; it’s shorter and clearer to call List.duplicate(:ok, 10). But you have to import Ecto.Query to use its macros. I’ve used a function-local import when only one function in a module needs import Ecto.Query, but it’s been flagged in code review.

When, if ever, would you use import this way?

2 Likes