design icon indicating copy to clipboard operation
design copied to clipboard

Mutable state within a package

Open hadley opened this issue 4 years ago • 1 comments

i.e. the <- new.new(parent = emptyenv()) or similar.

https://twitter.com/ID_AA_Carmack/status/575788622554628096 via @jimhester

hadley avatar May 19 '21 19:05 hadley

Note about using this approach in a package re: caching value.

Context: I am calling an API and want to cache the list result. I am using an internal environment in the package, and tried the the$ convention. For caching, I used rlang::env_cache()

# Defining internal state value would be this way
the$active_version <- "2.10"
# Resetting the state to no active version would be mean setting to NULL or ""
the$active_version <- NULL # ""

# But caching value would require `env_cache`
get_cached_val <- function() { env_cache(the, "val", default) }
# Resetting / clearing the cache can't be done by setting to NULL
the$val <- NULL
# because cached value would still be return by `env_cache`.
# It requires `env_unbind()` probably
env_unbind(the, "val")

For this type of usage, is this still interesting using the$val <- over using env_bind() ?

Should "unset state" be a value with NULL or an unbinded value ? In both case the$val returns NULL but in one case env_has(the, "val") is FALSE. When env_has(the, "val") is TRUE in any case, value can't currently be cached with env_cache()

library(rlang)
the <- new_environment()
the$val
#> NULL
env_has(the, "val")
#>   val 
#> FALSE
the$val <- NULL
env_has(the, "val")
#>  val 
#> TRUE
the$val
#> NULL

I am putting this here for thoughts - no expectation right now on an answer

cderv avatar Sep 10 '21 14:09 cderv