| defer {withr} | R Documentation |
Similar to on.exit(), but allows one to attach
an expression to be evaluated when exiting any frame currently
on the stack. This provides a nice mechanism for scoping side
effects for the duration of a function's execution.
defer(expr, envir = parent.frame(), priority = c("first", "last"))
defer_parent(expr, priority = c("first", "last"))
expr |
|
envir |
|
priority |
|
defer works by attaching handlers to the requested environment (as an
attribute called "handlers"), and registering an exit handler that
executes the registered handler when the function associated with the
requested environment finishes execution.
Kevin Ushey
# define a 'scope' function that creates a file, and
# removes it when the parent function has finished executing
scope_file <- function(path) {
file.create(path)
defer_parent(unlink(path))
}
# create tempfile path
path <- tempfile()
# use 'scope_file' in a function
local({
scope_file(path)
stopifnot(file.exists(path))
})
# file is deleted as we leave 'local' scope
stopifnot(!file.exists(path))
# investigate how 'defer' modifies the
# executing function's environment
local({
scope_file(path)
print(attributes(environment()))
})