memoise icon indicating copy to clipboard operation
memoise copied to clipboard

Constructed function environment not quite right

Open hadley opened this issue 4 years ago • 2 comments

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)

hadley avatar Nov 16 '21 14:11 hadley

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).

wch avatar Nov 16 '21 15:11 wch

Yeah, maybe make child of base environment?

hadley avatar Nov 16 '21 18:11 hadley