r-lib / R6

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

Easy access to private components for debugging purposes #40

Closed jankowtf closed 9 years ago

jankowtf commented 9 years ago

This is actually not an issue but probably just me not completely understanding the internal structure of R6 objects yet ;-)

What's the easiest way to access private components (fields or functions) of R6 instances for debugging purposes?

Consider the following example:

MyClass <- R6Class(
  classname = "MyClass",
  public = list(
    x = "character",
    initialize = function(
      x = "a"
    ) {
      self$x <- x
    }
  ),
  private = list(
    y = file.path(self$x, "b"),
    foo = function() {
      "I'm doing something useful"
    }
  )
)
inst <- MyClass$new()

Even in non-portable mode, I like to be specific about self-references and thus usually use self$* throughout respective class components instead of <<-. When wanting to test out things on an atomic level, I can do self <- inst and thus have access to all public components for "stand-alone atomic debugging".

But how would I do that for private components in a somewhat similar ("easy") way? I'm looking (hoping) for something like this: private <- inst$<private-env>.

I did manage to inspect the internal object structure of R6 classes and thus access private components like so:

MyClass <- R6Class(
  classname = "MyClass",
  public = list(
    x = "character",
    initialize = function(
      x = "a"
    ) {
      self$x <- x
      private$internal_env <- sys.frames()[[1]]
    },
    getInternalEnvironment = function() private$internal_env
  ),
  private = list(
    y = file.path(self$x, "b"),
    foo = function() {
      "I'm doing something useful"
    },
    internal_env = "environment" 
  )
)
inst <- MyClass$new()
env <- inst$getInternalEnvironment()
ls(env)
> ls(env$private_bind_env)
[1] "foo"          "internal_env" "y"     
private <- env$private_bind_env
> private$y
[1] "a/b"
> private$foo()
[1] "I'm doing something useful"

But that seems pretty "involved" ;-) Is there a simpler way for debugging purposes?

Thanks a lot, Janko

PS: Once again: awesome package/approach!

wch commented 9 years ago

Answered in #41.

Glad you find R6 to be useful!