Hong Ooi
Hong Ooi

Reputation: 57686

How to detect an empty quosure in rlang?

f <- function(x) enquo(x)

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

None of these work:

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

Upvotes: 8

Views: 873

Answers (2)

Lionel Henry
Lionel Henry

Reputation: 6803

You can use quo_is_missing(x), which is an alias for is_missing(quo_get_expr(x)).

Upvotes: 11

MichaelChirico
MichaelChirico

Reputation: 34723

Examining the print method for class quosure suggests it gets the "empty" attribute like so:

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

Unfortunately, env_type is not exported, and neither are the functions env_type calls (ultimately heading to the C function rlang_is_reference)

You can get it more directly (TRUE/FALSE) as:

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

Print method for quosure:

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

I'm not familiar enough with rlang to state with certainty, but this appears to be a way to get what you want using exported functions:

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

Though I must be missing something, since rlang:::is_reference is not using identical.

Upvotes: 3

Related Questions