butcher icon indicating copy to clipboard operation
butcher copied to clipboard

potential catch-all function to remove environments for unsupported packages?

Open klin333 opened this issue 5 years ago • 0 comments

I wrote a bit of code from a few years ago to recursively remove all .Environment attributes from an object and all its sub objects. It was a bit of a hack job when I did it, but I think it can work as a generic axe_env for most if not all model objects?

It's probably on the dangerous side given it attempts to null all .Environment, but given environments are the usual culprit for the most intolerable disk-space blow ups, this may still be a useful warned fallback for unsupported package objects? The alternative of manually defining what to remove gets time consuming when dealing with packages such as mgcv/scam and rstan/brms

axe_env <- function(obj) {
  sani <- function(o) {attr(o, ".Environment") <- NULL; o}
  obj <- sani(obj) 
  attrs <- attributes(obj)
  attrs <- sani(attrs)
  if(is.list(attrs)) {
    for(index in names(attrs)) {
      attrs[[index]] <- axe_env(attrs[[index]])
    }
    attributes(obj) <- attrs
  }
  if(is.list(obj)) {
    for(index in names(obj)) {
      obj[[index]] <- axe_env(obj[[index]])
    }
  }
  obj
}

klin333 avatar Oct 12 '20 05:10 klin333