R6 inherit does not carry information of the inherited class when used in a function

60 Views Asked by At

See example code:

myfunc <- function(inherit) {
  return(R6::R6Class("Derived", inherit = inherit)) 
}

Base <- R6::R6Class("Base")
Derived <- R6::R6Class("Derived", inherit = Base)
Derived2 <- myfunc(Base)
print(Derived)
print(Derived2)

Despite being technically equivalent, the first print statement reports:

<Derived> object generator
  Inherits from: <Base>
  Public:
    clone: function (deep = FALSE) 
  Parent env: <environment: 0x7fdf63a6cf18>
  Locked objects: TRUE
  Locked class: FALSE
  Portable: TRUE

While the second reports:

<Derived> object generator
  Inherits from: <inherit>
  Public:
    clone: function (deep = FALSE) 
  Parent env: <environment: 0x7fdf63afb8b8>
  Locked objects: TRUE
  Locked class: FALSE
  Portable: TRUE

How can I change the function myfunc so that the appropriately scoped name is used instead of the internal name inherit?

1

There are 1 best solutions below

5
MrFlick On

The R6Class function uses non-standard evaluation. You could do

myfunc <- function(inherit) {
  eval.parent(substitute(R6::R6Class("Derived", inherit = inherit)))
}

to get the same output. That will resolve the inherit value to the value that was passed into the function