r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
405 stars 56 forks source link

with(r6obj, {}) throws an error #111

Closed richierocks closed 7 years ago

richierocks commented 7 years ago

To reproduce:

library(R6)
test_factory <- R6Class(
  "Test",
  public = list(
    data = 1
  )
)

test <- test_factory$new()

with(test, data) # OK

with(test, {data}) 
## Error in eval(expr, envir, enclos) : could not find function "{"

I know I can work around this by doing test$data, but not being able to find { seems interestingly weird and I wonder what is going on.

wch commented 7 years ago

It's because the R6 object is an environment whose parent environment is the empty env. When you run with(test, {data}), it evaluates the expression {data} in the test environment. R searches test for {, doesn't find it, and then searches the ancestor environments of test; because the only ancestor the empty env, which contains nothing, it throws that error.

You'd get a similar error if you were to do this:

with(test, 1+1)
# Error in eval(expr, envir, enclos) : could not find function "+"

Or this:

e <- new.env(parent = emptyenv())
with(e, 1+1)
# Error in eval(expr, envir, enclos) : could not find function "+"

You may be able to write a with.R6 method that handles this case, but it's highly unlikely that it would be merged in this repo, because I generally avoid using with.