Skip to content

S7_data<- doesn't allow updating attributes like names #478

@t-kalinowski

Description

@t-kalinowski

Note that the name of the 3rd entry is missing after updating.

library(S7)
write_once_list <- new_class("write_once_list",
  class_list,
  constructor = function(...) new_object(list(...)),
  validator = function(self) {
    if(anyDuplicated(nms <- names(self)))
      paste0("names not all unique. duplicates: ",
             paste0(unique(nms[duplicated(nms)]), collapse = ", "))
  }
)

method(`$<-`, write_once_list) <- 
method(`[[<-`, write_once_list) <- function(x, name, value) {
  .x <- S7_data(x)
  if (hasName(.x, name))
    stop("entry exists: ", name)
  .x[[name]] <- value
  S7_data(x) <- .x
  x
}

w <- write_once_list(x = 3, y = 4)

w
#> <write_once_list> List of 2
#>  $ x: num 3
#>  $ y: num 4
w$bar <- 1

w
#> <write_once_list> List of 3
#>  $ x : num 3
#>  $ y : num 4
#>  $ NA: num 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions