In the following example, I try to get an element from a grandparent environment using env_get
. The first bit works as expected.
library(rlang)
e1 <- env(a = 'a')
# works as expected
f <- function() {
env_get(
env = caller_env(),
nm = 'a',
inherit = TRUE,
default = 'not found')
}
exec(f, .env = e1)
#> [1] "a"
# two levels deep of function calls doesn't work even though inherit = TRUE
g <- function() f()
exec(g, .env=e1)
#> [1] "not found"
# modifying the depth of caller_env in f does work
f <- function() {
env_get(
env = caller_env(2), # <------ changing this
nm = 'a',
inherit = TRUE,
default = 'not found')
}
exec(g, .env=e1)
#> [1] "a"
Created on 2021-12-28 by the reprex package (v2.0.1)
I expected that the second bit, calling exec
on g
with .env=e1
would work, as the call to env_get
has inherit=TRUE
. My understanding was that it would look in the caller_env
, find nothing, and look in its parent to find "a"
, but this did not work. Further confusing me on this is what when I explicitly instruct env_get
to look 2 levels up, this does work.
Am I misunderstanding something about how this inheritance should work?