How to check if a module exists? How to check if a module has a function?


So I want to check if a module exist and has some function defined. For example, I want to check if I have module Foo with foo/2 function defined. Any ideas?


Looks like I can check for module existence this way:

{:module, String}


@hubertlepicki may be it will help?


Yes! Thank you @dgamidov seems like I can do


that returns list of function names with arity. Perfect.


@hubertlepicki Code.ensure_loaded/1 doesn’t check if it exists. It checks if it is loaded and if not then it is loaded (or tries to load it):

Ensures the given module is loaded.

If the module is already loaded, this works as no-op. If the module was not yet loaded, it tries to load it.


For posterity: It is more Elixir-like to use Foo.__info__(:functions).

:functions is an alias of the Erlang-specific :exports, but a lot clearer. Also, __info__/1 is the Elixir-wrapper around :erlang.module_info/1 and allows slightly more atoms as input (such as :macros).

See the docs for more information.

Also note that there are many functions inside the stdlib Module module , but most (except for __info__/1) only work during compile-time.


Do you want to test if the module is loaded and exports a specific function, or you do you want to test if there exists a module which you can reach at all containing the function? If it is the first then you have the function :erlang.function_exported(module, function, arity). I don’t know if there is an Elixir interface function. The other alternative has already been covered here, but be aware that the solutions, when they check, will load the module if it not already loaded.


yup, I am good with loading module if it hasn’t been loaded at all. I want to know if I can call this Module.function. If I load it doing that, it’s also ok.


Another thing that you might like to look at, are Behaviours. If your current use-case is to have later-defined modules (e.g. made by users of your library) that have to follow a fixed specification you provide, then Behaviours are the way to go.


Elixir has the function Kernel.function_exported?/3, which returns true if the speficied module is loaded and contains a public function with the given arity, otherwise false.