r-lib / R6

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

locked objects + derived classes #129

Open kevinushey opened 6 years ago

kevinushey commented 6 years ago

The following snippet of code fails:

library(R6)

Base <- R6Class(
  "Base",
  public = list(
    initialize = function() {
      self[["Hello"]] <- 1
    }
  ),
  lock_objects = FALSE
)
Base$new()  # okay

Derived <- R6Class("Derived", inherit = Base)
Derived$new()  # barf

The error:

> Derived$new()
Error in self[["Hello"]] <- 1 : 
  cannot add bindings to a locked environment

Should derived classes also inherit the lockedness from their parent environment?

wch commented 6 years ago

The behavior you're proposing does seem reasonable... but then what do you suggest as the default value for lock_objects?

kevinushey commented 6 years ago

I would lean towards lock_objects = FALSE, unless modifying that makes it too easy for users to do things that could break R6 in weird ways. (I think modifying properties on self is probably fine in most cases?)

wch commented 6 years ago

I think it's too late to change the default behavior to not lock objects -- and I think that it's good that they're locked by default.

What I meant was, it seems reasonable to allow inheriting the lock status, but if we were to change to that behavior, the current default of lock_objects = TRUE doesn't make sense. So the question is what could it be changed to that makes top-level classes default to being locked, but also makes subclasses inherit the lock status by default?