如何确定从哪个模块导入了 elixir 中的特定功能

How to determine from which module a specific function was imported in elixir

当通过在某个中间模块上调用 use 包含多个外部模块时,是否有一种简单的方法来确定给定方法实际定义在哪个模块中?

例如:

defmodule ModuleB do
  def method_b do
  end
end    

defmodule ModuleA do
  # imports ModuleB implicitly
  use SomeModuleImportingModuleB

  def method_a
    # how to determine this is ModuleB.method_b?
    method_b
  end
end

我找到了一个适合我的解决方案,方法是使用 & 捕获函数然后检查它:

def method_a
  IO.inspect &method_b/0 
  # outputs &ModuleB.method_b
  method_b
end

每个模块都定义了一个__info__函数,您可以通过它查看该模块导出的函数:

IO.inspect ModuleB.__info__(:exports)
# => [method_b: 0, module_info: 0, module_info: 1, __info__: 1]

请注意,当使用 use 时,相关模块可能会将代码直接注入到正在定义的模块中并动态创建函数 - 这可能会导致 [=] 中未定义的函数变得可用13=]模块。