RConsortium / S7

S7: a new OO system for R
https://rconsortium.github.io/S7
Other
386 stars 32 forks source link

Made properties starting with a dot not printable #402

Closed rikivillalba closed 2 months ago

rikivillalba commented 2 months ago

Is there a possibility to hide by default properties starting with a dot at least in the default print and str methods? There could be the case when you use a "dynamic" property with getter and setter, and the true value is stored in an internal property you want to hide. i.e.:

library(S7)

someclass <- new_class("someclass", properties = list(
  .action = class_any,
  action = new_property(getter = \(self) self@.action, 
                        setter = \(self, value) {
                          self@.action <- value
                          self })))

x <- someclass()
x@action <- "some action"

print(x)
#> <someclass>
#>  @ .action: chr "some action"
#>  @ action : chr "some action"

So I find this better:

print(x)
#> <someclass>
#>  @ action : chr "some action"

print(x, all_names = TRUE)
#> <someclass>
#>  @ .action: chr "some action"
#>  @ action : chr "some action"

Such a behaviour will provide a python-like soft encapsulation with dot names. Also will equate the behaviour of base::ls() (and that of the unif file system)

hadley commented 2 months ago

There's not technically a need for that:

library(S7)

someclass <- new_class("someclass", properties = list(
  action = new_property(
    getter = function(self) self@action,
    setter = function(self, value) {
      self@action <- toupper(value)
      self 
    }
  )
))
x <- someclass()
x@action <- "some action"
x@action
#> [1] "SOME ACTION"

x
#> <someclass>
#>  @ action: chr "SOME ACTION"

Created on 2024-05-26 with reprex v2.1.0

rikivillalba commented 2 months ago

Sorry i was not aware of it, but my conclusion came because evaluating the property without prior assignment exhausted the stack (so I thought that self@action simply recursed the getter, that is not the case as your example shows).

However i get the error when the prop is not initialized.

In my case this happens:

library(S7)

someclass <- new_class("someclass", properties = list(
  action = new_property(
    getter = function(self) self@action,
    setter = function(self, value) {
      self@action <- toupper(value)
      self 
    },
    default = "some action"
  )
))
x <- someclass()
x@action

#> Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

Created on 2024-05-26 with reprex v2.1.0

rikivillalba commented 2 months ago

I'll close this thread and open a new one with the appropiate name