Elixir 1.4/master: warning: module attribute @attr_name was set but never used

Hey, I’m testing my project on latest releases of Elixir (both 1.4 and master) and also on both I got message like:

warning: module attribute @attr_name was set but never used

It’s really good feature! Thanks Elixir developers!

I have a suggest for it.
Example code:

defmodule Example do
  @lorem_ipsum "Lorem ipsum ..."

  def sample(), do: get_sample(:lorem_ipsum)

  defp get_sample(name), do: Module.get_attribute(__MODULE__, name)
end

defmodule AnotherExample do
  @lorem_ipsum "Lorem ipsum ..."

  def sample(), do: "Lorem ipsum ..."
end

Of course my project have much more code that should not be saved in separate files (like regular expressions).

As you can see I will get this warning for both modules (of course it’s ok), but in different situations. In first case I used a method &get_sample/1 as shortcut for &Module.get_attribute/2 and in second case I forgot about use attribute (for example old version of writing same things).

I suggest to separate two messages like:

  1. In case &Module.get_attribute/2 is not called anywhere in code for this module that has this attribute:

warning: module attribute @attr_name was set but never used

  1. In case &Module.get_attribute/2 is called anywhere in code for this module that has this attribute:

warning: module attribute @attr_name was set but probably never used

Why? For example in bigger project I can filter these warnings and focus on situations where I’m 100% sure that I forgot about attribute(s).

What do you think about it? Is it possible to separate both situations?

1 Like

This sample code does not work. :slight_smile: Module attributes are compile time. Which means that, when the module gets compiled, which is effectively when you are able to call sample, the module attribute no longer exists.

I just tried on IEx:

iex(2)> Example.sample
** (ArgumentError) could not call get_attribute on module Example because it was already compiled

The only time you can actually call Module.get_attribute in a module is when it is being defined and, in case we do so, we will correctly mark the attribute as used.

Maybe there is a scenario or a condition we didn’t consider but I am pretty sure you are indeed not using the module attribute in both examples above.

3 Likes

Wow, how I could missed it in documentation :icon_surprised: Thanks @josevalim for explanation.