"Invalid" module attribute xxx was set but never used?

I wonder if there’s a way to conditionally define functions and not have this warning go off.

In my config I have this simple line
config :my_app, :environment, config_env()

So with a module

defmodule MyApp.Example do
  @env Application.compile_env(:my_app, :environment)
  @attribute "This will trigger a warning"
  
  if @env == :prod do
    def some_func(), do: @attribute
  else
    def some_func(), do: "no attribute"
  end
end

In development (or any environment that is not production) this will cause a warning “module attribute @attribute was set but never used”.

Fully aware that I might be doing something I shouldn’t be doing, and it’s a very rare occurrence, I just need to really make sure certain things only have active code in production and nowhere else. The warning is still the same if I use a guard.

You can move the assignment of the module attribute into the if branch as well.

1 Like

This may not be relevant as your post is probably just an example, but as the docs mention it is generally better to do this:

def some_func, do: "Some literal"

…instead of using an attribute. I mention this only because many new to Elixir (including myself, once) find this pretty unintuitive coming from other languages where something like this might allocate objects on every call.

But again, if this is not actually what you’re doing then ignore this reply :slight_smile:

1 Like