Check if Elixir module exports a specific function

How do you check if a module has opened a Elixirspecific public method? How do you check if a function has been exposed with a specific arity?

Does not work:

  • Map.methods
  • Map.functions
  • Map.has_function(:keys)
+5
source share
3 answers

Based on the answer here and the discussion on the forum here , there are several ways to do this:


Check if a function exists for the module

You can check if the function name is present as a key in Map.__info__(:functions)

module = Map
func   = :keys

Keyword.has_key?(module.__info__(:functions), func)
# => true

Check if a function exists with a certain arity

To test with, aritywe can use Kernel.function_exported?/3:

Kernel.function_exported?(Map, :keys, 1)         # => true
Kernel.function_exported?(Map, :keys, 2)         # => false

Updated to use function from the Kernel module instead of the :erlang module

+11

Module.defines?/2:

defmodule M do
  __MODULE__ |> Module.defines?({:keys, 1})
end

:

Map |> Module.defines?({:keys, 1})

** (ArgumentError) defines? Map,

(elixir) lib/module.ex:1169: Module.assert_not_compiled!/2
(elixir) lib/module.ex:753: Module.defines?/2

:

iex(59)> Map.__info__(:functions)[:get]           
#⇒ 2 # minimal arity, truthy
iex(60)> Map.__info__(:functions)[:nonexisting]
#⇒ nil # no such function, falsey
iex(61)> !!Map.__info__(:functions)[:get]      
#⇒ true # erlang style
iex(62)> !!Map.__info__(:functions)[:nonexisting]
#⇒ false # erlang style
0

Use Kernel.function_exported?/3as follows:

function_exported?(List, :to_string, 1)
# => true
0
source

Source: https://habr.com/ru/post/1657547/


All Articles