Am I doing this right? (rlang::dots_list / !!!)

I'm trying something with a package function. But I'm getting an error downstream that is making me wonder if I am doing things right. Or perhaps I am overcomplicating the use of ... and friends.

my_fun <- function(...) {
  args <- rlang::dots_list(
    param1 = "a",   # some default values
    param2 = "b",
    ...,
    .homonyms = "last" # allow user-supplied args to supersede defaults
  )

  param1 <- f(args$param1)
  param2 <- f(args$param2)

  args <- rlang::dots_list(
    !!!args, # splice in original defaults
    param1,
    param2,
    .homonyms = "last",
    .named = TRUE
  )

  output_fun(!!!args)
}

The function can use a long list of arguments, but mostly I am happy with them having the default values. But I want to be able to pass in a different value occasionally via the dots. The defaults are listed in the args list at the top of the function, but anything passed in by the user should supersede the defaults.

The reason I am doing this is to avoid having lots of named function parameters with default values, to document. The output function at the end then uses the updated list of args.

One of the args passed on my output function is a date-time value that behaves fine when I pass it to output_fun like this:

output_fun(param1, param2, dttm = args$dttm, another = args$another)

but when I include it within this wrapper function with the dots/splice setup I get an error downstream: Error in !args : invalid argument type which the traceback tells me is something to do with the datetime value.

I feel like its hard to support you without some kind of reprex; and that it would be much harder for me to try to reprex it than say for you to do it.
That leaves me only really being able to point out some simple syntax stuff that is probably not relevant to your actual code

Theres a comma missing in between the following part:

 .homonyms = "last"
    .named = TRUE

when f() is called on param1, param2, there are no guarantees of the presence of either param1 or param2 so this would seem likely to throw errors.

1 Like

Thanks, yes I will try to create an actual reprex instead of this pseudocode. Trying to abstract from my actual function rather late at night!

I have amended the f() lines in my example meanwhile.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.