mlr-org / mlr3misc

Miscellaneous helper functions for mlr3
https://mlr3misc.mlr-org.com
GNU Lesser General Public License v3.0
11 stars 2 forks source link

need something that removes environments from functions #35

Closed mb706 closed 3 years ago

mb706 commented 4 years ago

I want to save an anonymous function in an object and serialize that object, but that object should not grow huge. It is then necessary that the function's environment hierarchy doesn't contain too much other stuff.

Usecase:

x = 1
large_obj = [huge object that takes lots of memory]
want_to_serialize = function(arg) return(arg + x)
saveRDS(want_to_serialize, "savefile.rds")

want_to_serialize's environment now contains large_obj and the savefile grows large. Instead I would want a function detachEnv(fun, keep, basis):

want_to_serialize_lean = detachEnv(want_to_serialize, keep = "x")
saveRDS(want_to_serialize_lean, "savefile.rds")

code for this:

# removes the environment from fun and potentially wraps it in a new environment
detachEnv <- function(fun, keep = character(0), basis = topenv(parent.frame())) {
  assertEnvironment(basis)
  assertCharacter(keep, any.missing = FALSE)
  assertFunction(fun)
  if (length(keep)) {
    keepvals <- mget(keep, parent.frame(), inherits = TRUE)
    basis <- new.env(parent = basis, size = length(keepvals))
    mapply(assign, names(keepvals), keepvals, MoreArgs = list(envir = basis))
  }
  environment(fun) <- basis
  fun
}

name up for debate

mllg commented 4 years ago

https://github.com/r-lib/carrier/

Something like this?

berndbischl commented 4 years ago

i think they do this in tidymodels too

mb706 commented 4 years ago

this, only without the tidyverse awfulness

mllg commented 3 years ago

Closed in #50 ?