r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
489 stars 131 forks source link

FR: add `env` argument to `is_missing()` #1715

Open DanChaltiel opened 1 month ago

DanChaltiel commented 1 month ago

Hi,

In some cases, it can be interesting to know if an argument is missing from the caller frame.

For instance, I'd like to propose a standard way to handle arguments through options when they are missing. Here, being able to check the missingness from inside a helper would be very handy.

Here is a reprex with a clumsy workaround:

library(rlang)

is_miss_bad = function(x, env=parent.frame()){
  is_missing(x)
}
is_miss_good = function(x, env=parent.frame()){
  xname = caller_arg(x)
  eval(parse(text=paste0("missing(",xname,")")), envir=env)
}

f = function(a=2){
  cat("bad:", is_miss_bad(a), "\n")
  cat("good:", is_miss_good(a))
  invisible()
}

f()
#> bad: FALSE 
#> good: TRUE

Created on 2024-05-30 with reprex v2.1.0

Note that is_miss_bad() would actually work fine if a didn't have a default value.

Would you consider adding this feature to rlang::is_missing()?

lionel- commented 1 month ago

I think I'd rather fix either is_missing() or missing() in base. This env argument doesn't seem ergonomic.

DanChaltiel commented 3 days ago

I edited my post to show the proper FR demand. However, I am not sure to understand, what do you mean by "fix in base"? Also, what would you suggest instead of env? If you don't think this would be a nice improvement to rlang::is_missing(), would you have a suggestion on a better way to do that than eval(parse(...))?