r-lib / memoise

Easy memoisation for R
https://memoise.r-lib.org
Other
317 stars 59 forks source link

Constructed function environment not quite right #134

Open hadley opened 2 years ago

hadley commented 2 years ago

Ideally the memoised function would be insulated/namespaced so it's not affected by the global environment

library(memoise)

f <- memoise(function(x) 10)
f()
#> [1] 10

setdiff <- function(...) stop("!")
f()
#> Error in setdiff(names(default_args), names(called_args)): !

Created on 2021-11-16 by the reprex package (v2.0.1)

wch commented 2 years ago

What would the memoized function have for a parent?

Currently, it creates an environment which is a child of the calling environment:

library(memoise)
f <- function(x) 10
fm <- memoise(f)
environment(fm)
#> <environment: 0x10fab1388>
pryr::parenvs(fm)
#>   label                      name
#> 1 <environment: 0x10fab1388> ""  
#> 2 <environment: R_GlobalEnv> ""

A naive alternative would be to create an environment which is a child of the memoise namespace, but then the memoized function would have a dependency on the memoize package, which is something I think we want to avoid.

Maybe it would make sense to make the memoized function environment a sibling of the global env? Or, we may even be able to make it a child of the base environment (or base namespace).

hadley commented 2 years ago

Yeah, maybe make child of base environment?