Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mutable state within a package #126

Open
hadley opened this issue May 19, 2021 · 1 comment
Open

Mutable state within a package #126

hadley opened this issue May 19, 2021 · 1 comment

Comments

@hadley
Copy link
Member

hadley commented May 19, 2021

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

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

cderv added a commit to cderv/pandoc that referenced this issue Sep 10, 2021
cderv added a commit to cderv/pandoc that referenced this issue Sep 10, 2021
@cderv
Copy link

cderv commented Sep 10, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants