How to bring the current context when a module is being executed into a module?

I have this:

defmodule MyTest1 do
  def print_data do
    IO.puts("***this module: #{__MODULE__}")

If I call it from within other module, it’ll still print the name of the original module --> Elixir.MyTest1.

How to change it such that it’ll print the name of a module it’s being called from? Without having to pass __MODULE__ to the function call.

One way would be to use a macro. But I think it’s generally recommended to only use macros if you really need them or if it really reduces boilerplate.

You can use __CALLER__

  defmacro print_data do
    quote do
      IO.puts("***this module: #{unquote(__CALLER__.module)}")

(edit: added __CALLER__ info)


__MODULE__ is evaluated at compile time, that is why it will always show the module it is called in.

1 Like