When dealing with object holding pointers that are only valid during a
single session, it would be convenient to exclude them from being saved
with the session image. (I am assuming that `quit` calls `save.image`
before quitting or is it internal?) Currently they are saved with the
pointer converted to NULL. Its a bit surprising for users not realizing the
object is no longer valid.

My thought is to designate a class name (perhaps "no.save") and exclude
anything that inherits from that. I've hacked a quick implementation below.
I did not issue a warning, but it would be a simple fix.

Does anyone else see this as useful?

THK

-- 
http://www.keittlab.org/

.new.save.image = function (file = ".RData", version = NULL, ascii = FALSE,
compress = !ascii,
                            safe = TRUE, omit.no.save = TRUE)   # added
"omit.no.save" argument
{
  if (!is.character(file) || file == "")
    stop("'file' must be non-empty string")
  opts <- getOption("save.image.defaults")
  if (is.null(opts))
    opts <- getOption("save.defaults")
  if (missing(safe) && !is.null(opts$safe))
    safe <- opts$safe
  if (missing(ascii) && !is.null(opts$ascii))
    ascii <- opts$ascii
  if (missing(compress) && !is.null(opts$compress))
    compress <- opts$compress
  if (missing(version))
    version <- opts$version
  if (safe) {
    outfile <- paste0(file, "Tmp")
    i <- 0
    while (file.exists(outfile)) {
      i <- i + 1
      outfile <- paste0(file, "Tmp", i)
    }
  }
  else outfile <- file
  on.exit(file.remove(outfile))

  ### Omit objects inheriting from "no.save" ###

  objns <- ls(envir = .GlobalEnv, all.names = TRUE)

  if ( omit.no.save )  ### make part of options?
    objns <- subset(objns, sapply(objns, function(x)
    {
      ! inherits(get(x, envir = .GlobalEnv), "no.save")
    }))

  save(list = objns, file = outfile,
       version = version, ascii = ascii, compress = compress,
       envir = .GlobalEnv, precheck = FALSE)

  ### End code changes ###

  if (safe)
    if (!file.rename(outfile, file)) {
      on.exit()
      stop(gettextf("image could not be renamed and is left in %s",
                    outfile), domain = NA)
    }
  on.exit()
}

setClass("no.save")
setClass("test.class", slots = c(s1 = "externalptr"))
setIs("test.class", "no.save")
reg.obj = "regular object"
no.save.obj = new("test.class")
.image.file = tempfile()
save.image(.image.file)
rm(reg.obj, no.save.obj)
load(.image.file)
print(ls())
unlink(.image.file)
.new.save.image(.image.file)
rm(reg.obj, no.save.obj)
load(.image.file)
print(ls())
unlink(.image.file)

        [[alternative HTML version deleted]]

______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

Reply via email to