如何检测rlang中的空quosure?

How to detect an empty quosure in rlang?

f <- function(x) enquo(x)

e <- f()
#<quosure: empty>
#~

None 这些作品:

> is_empty(e)
[1] FALSE
> is_missing(e)
[1] FALSE
> is_false(e)
[1] FALSE
> is_quosure(e)
[1] TRUE

检查 class quosure 的打印方法表明它获取 "empty" 属性,如下所示:

rlang:::env_type(get_env(e))
# [1] "empty"

遗憾的是,env_type 未导出,函数 env_type 调用也未导出(最终转到 C 函数 rlang_is_reference

你可以更直接地获取它(TRUE/FALSE)如:

rlang:::is_reference(get_env(e), empty_env())
# [1] TRUE

quosure 的打印方法:

rlang:::print.quosure
# function (x, ...) 
# {
#     cat(paste0("<quosure: ", env_type(get_env(x)), ">\n"))
#     print(set_attrs(x, NULL))
#     invisible(x)
# }

我对 rlang 不够熟悉,无法肯定地说,但这似乎是一种使用导出函数获得所需内容的方法:

identical(get_env(e), empty_env())
# [1] TRUE

虽然我一定遗漏了一些东西,因为 rlang:::is_reference 没有使用 identical

您可以使用 quo_is_missing(x),这是 is_missing(quo_get_expr(x)) 的别名。