R6 icon indicating copy to clipboard operation
R6 copied to clipboard

shadowing a regular binding with an active binding

Open romainfrancois opened this issue 5 years ago • 1 comments

library(R6)

A <- R6Class("A", 
  public = list(
    foo = 3L
  )
)

B <- R6Class("B", inherit = A, 
  active = list(
    foo = function() 91
  )
)

b <- B$new()
#> Error in makeActiveBinding(name, active[[name]], public_bind_env): symbol already has a regular binding

Can we do one of these here:

https://github.com/r-lib/R6/blob/master/R/new.R#L121

  • check that the foo binding already exist in public_bind_env and remove it. (I can submit a PR easily, and I think it's the right approach)

  • give a better error message, explaining what the problem is and what classes and binding are involved. it's easy enough to see what happens in the reprex, but I've been struggling since yesterday with a version of this in 📦 arrow. I guess I can also submit a PR for this option.

romainfrancois avatar Nov 27 '18 13:11 romainfrancois

This looks related to #166 and #168. I think that for subclasses there should be better checks that ensure that public/private/active items are not overridden by items from another category. This would be the second solution you proposed.

Allowing a field to be overridden by an active binding could result in tricky problems. For example, if x is an active binding, in a method you can access super$x. However, if x is a regular (public) field, there is no super$x, only self$x.

library(R6)

A <- R6Class("A",
  public = list(
    x = 1
  ),
  active = list(
    y = function() 1
  )
)

B <- R6Class("B", inherit = A,
  public = list(
    get_self_x  = function() self$x,
    get_super_x = function() super$x
  ),
  active = list(
    y = function() super$y + 1
  )
)

b <- B$new()
b$get_self_x()
#> [1] 1
b$get_super_x()
#> NULL
b$y
#> [1] 2

wch avatar Nov 27 '18 18:11 wch