Skip to contents

Functions may be named or anonymous. When functions are used as a parameter, for error reporting it is sometimes useful to be able to refer to the function by the name it is given when it is defined. Sometimes functions can have multiple names.

Usage

get_fn_name(fn = rlang::caller_fn(), fmt = "%s", collapse = "/")

Arguments

fn

a function definition (defaults to the function from which get_fn_name is called)

fmt

passed to sprintf with the function name e.g. %s() will append brackets

collapse

passed to paste0 in the case of multiple matching functions. set this to NULL if you want the multiple function names as a vector.

Value

the name of the function or "<unknown>" if not known

Examples

# detecting the name when function used as a parameter. This is the 
# primary use case for `get_fn_name`
testfn2 = function(fn) {
  message("called with function: ",get_fn_name(fn))
}

testfn2(mean)
#> called with function: mean
testfn2(utils::head)
#> called with function: utils::head
testfn2(testfn2)
#> called with function: testfn2

# detecting the name of a calling function, an unusual use case as this is
# normally known to the user.
testfn = function() {
  message(get_fn_name(fmt="%s(...)")," is a function")
}

`test fn 2` = testfn
test_fn_3 = testfn
testfn()
#> test_fn_3(...)/`test fn 2`(...)/testfn(...) is a function