在不同环境中调用时,部分粘合功能不起作用

问题描述

我在我正在处理的项目中使用了 partialised glue function,这样我们就可以使用商定的分隔符,而不必一直告诉胶水。但是当我们在另一个函数中使用偏函数时,它停止工作:

library(purrr)
library(glue)

glue_query <- partial(glue,.open = "<<",.close = ">>")

# case 1: use partialised function in same scope
x <- 15
glue_query("There are <<x>> apples here!")
#> There are 15 apples here!

# case 2: use partialised function in different scope
myfunc_partialised <- function(y) {
  glue_query("The thing I called y is actually <<y>>")
}
myfunc_partialised(15)
#> Error in eval(parse(text = text,keep.source = FALSE),envir): object 'y' not found

# case 3: use function directly
myfunc_regular <- function(z) {
  glue("The thing I called z is actually <<z>>",.close = ">>")
}
myfunc_regular(15)
#> The thing I called z is actually 15

reprex package (v2.0.0) 于 2021 年 7 月 9 日创建

我感觉 glue_query 正在寻找要在它定义的环境中插入的对象,而不是在它调用的环境中。这就是这里发生的事情吗?我可以指导它使用调用环境吗?我想在我的整个包裹中使用它!

编辑:我知道 glue一个 .envir 参数来控制表达式在哪个环境中计算,但我不太确定使用什么来确保在这里玩得很好!

解决方法

似乎 partial() 确实让获得正确的环境变得更加困难。相反,您可以编写自己的包装器

glue_query <- function(...,.open = "<<",.close = ">>",.envir=parent.frame()) {
  glue(...,.open=.open,.close=.close,.envir=.envir)
}

这将适用于您提供的两个测试用例。

,

另一种选择是更改胶水的默认值,定义您的函数,重置默认值:

library(glue)
library(default)

default(glue) <- list(.open = "<<",.close = ">>")
glue2 <- glue
reset_default(glue)
#> function (...,.sep = "",.envir = parent.frame(),.open = "{",#>     .close = "}",.na = "NA",.transformer = identity_transformer,#>     .trim = TRUE) 
#> {
#>     glue_data(.x = NULL,...,.sep = .sep,.envir = .envir,.open = .open,#>         .close = .close,.na = .na,.transformer = .transformer,#>         .trim = .trim)
#> }
#> <bytecode: 0x0000000014c59d80>
#> <environment: namespace:glue>

# case 1: use partialised function in same scope
x <- 15
glue_query("There are <<x>> apples here!")
#> Error in glue_query("There are <<x>> apples here!"): could not find function "glue_query"
#> There are 15 apples here!

# case 2: use partialised function in different scope
myfunc_partialised <- function(y) {
  glue2("The thing I called y is actually <<y>>")
}
myfunc_partialised(15)
#> The thing I called y is actually 15

# case 3: use function directly
myfunc_regular <- function(z) {
  glue("The thing I called z is actually <<z>>",.close = ">>")
}
myfunc_regular(15)
#> The thing I called z is actually 15

reprex package (v0.3.0) 于 2021 年 7 月 9 日创建