butcher
butcher copied to clipboard
potential catch-all function to remove environments for unsupported packages?
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
}