Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of a function?

Tags:

erlang

Is it possible to know the name of a function in itself ?

a_function()->
    io:format("I am ~p!", [????]). % What to use here?
like image 287
Bertaud Avatar asked Feb 06 '11 18:02

Bertaud


People also ask

How do you print a function name in Python?

Use the __name__ Property to Get the Function Name in Python __name__ . It will then return the function name as a string. The below example declares two functions, calls them, and prints out their function names. Note that this solution also works with the imported and pre-defined functions.

How do you name a function in Python?

Method name in PythonUse only lowercase in method names. An underscore should separate words in a method name. Non-public method name should begin with a single underscore. Use two consecutive underscores at the beginning of a method name, if it needs to be mangled.

How do you call a function named my function?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.


2 Answers

Use the macro ?FUNCTION_NAME to get the name of the current function as an atom, and ?FUNCTION_ARITY to get the arity as an integer.

Example:

-module(test).

-export([a_function/2]).

a_function(_Foo, _Bar) ->
    io:write("I am ~p/~p!",[?FUNCTION_NAME, ?FUNCTION_ARITY]).
1> c(test).
{ok,test}
2> test:a_function(a, b).
I am a_function/2!

This was implemented in EEP-0045.

For Erlang Versions 18 and Older

In older Erlang versions, there's no simple way to get the current function name at compile time. You can however retrieve it at runtime:

{current_function, {M, F, A}} = process_info(self(), current_function)

Where A is the arity (number of arguments), not the actual arguments. The first argument to process_info/2 is a process ID which can be either the current process (self()) or an other process. For example:

1> process_info(self(), current_function).
{current_function,{erl_eval,do_apply,5}}

Note however, that while this would be functionally equivalent to the ?FUNCTION_NAME macro, it's much slower because it is evaluated in runtime.

like image 84
Adam Lindberg Avatar answered Oct 24 '22 23:10

Adam Lindberg


at runtime, you could throw an exception and check the top of the stacktrace.

foo() ->
    catch throw(away),
    [{Module, Fun, Arity} | _] = erlang:get_stacktrace(),
    io:format("I am ~p:~p/~p!~n",[Module, Fun, Arity]).
like image 45
butter71 Avatar answered Oct 24 '22 23:10

butter71