rlang (version 0.2.0)

fn_fmls: Extract arguments from a function

Description

fn_fmls() returns a named list of formal arguments. fn_fmls_names() returns the names of the arguments. fn_fmls_syms() returns formals as a named list of symbols. This is especially useful for forwarding arguments in constructed calls.

Usage

fn_fmls(fn = caller_fn())

fn_fmls_names(fn = caller_fn())

fn_fmls_syms(fn = caller_fn())

fn_fmls(fn) <- value

fn_fmls_names(fn) <- value

Arguments

fn

A function. It is lookep up in the calling frame if not supplied.

value

New formals or formals names for fn.

Details

Unlike formals(), these helpers also work with primitive functions. See is_function() for a discussion of primitive and closure functions.

Note that the argument names are taken from the closures that are created when passing the primitive to as_closure(). For instance, while the arguments of the primitive operator + are labelled e1 and e2, fn_fmls_names() will return .x and .y. Note that for many primitives the base R argument names are purely placeholders since they don't perform regular argument matching. E.g. this returns 5 instead of -5:

`-`(e2 = 10, 5)

To regularise the semantics of primitive functions, it is usually a good idea to coerce them to a closure first:

minus <- as_closure(`-`)
minus(.y = 10, 5)

See Also

call_args() and call_args_names()

Examples

Run this code
# NOT RUN {
# Extract from current call:
fn <- function(a = 1, b = 2) fn_fmls()
fn()

# Works with primitive functions:
fn_fmls(base::switch)

# fn_fmls_syms() makes it easy to forward arguments:
call2("apply", !!! fn_fmls_syms(lapply))

# You can also change the formals:
fn_fmls(fn) <- list(A = 10, B = 20)
fn()

fn_fmls_names(fn) <- c("foo", "bar")
fn()
# }

Run the code above in your browser using DataCamp Workspace