A set of functions to run code with safely and temporarily modified
global state. There are two sets of functions, those prefixed with
with_
and those with local_
. The former reset their state as soon as
the code
argument has been evaluated. The latter reset when they reach
the end of their scope, usually at the end of a function body.
Many of these functions were originally a part of the devtools package, this provides a simple package with limited dependencies to provide access to these functions.
with_collate()
/local_collate()
- collation orderwith_dir()
/local_dir()
- working directorywith_envvar()
/local_envvar()
- environment variableswith_libpaths()
/local_libpaths()
- library pathswith_locale()
/local_locale()
- any locale settingwith_makevars()
/local_makevars()
- Makevars variableswith_options()
/local_options()
- optionswith_par()
/local_par()
- graphics parameterswith_path()
/local_path()
- PATH environment variablewith_*()
andlocal_()
functions for the built in R devices,bmp
,cairo_pdf
,cairo_ps
,pdf
,postscript
,svg
,tiff
,xfig
,png
,jpeg
.with_connection()
/local_connection()
- R connections.with_package()
,with_namespace()
andwith_environment()
- to run code with modified object search paths.with_tempfile()
/local_tempfile()
- Create and clean up a temp file.with_file()
/local_file()
- Create and clean up a normal file.
There are also with_()
and local_()
functions to construct new
with_*
and local_*
functions if needed.
Sys.getenv("WITHR")
#> [1] ""
with_envvar(c("WITHR" = 2), Sys.getenv("WITHR"))
#> [1] "2"
Sys.getenv("WITHR")
#> [1] ""
with_envvar(c("A" = 1),
with_envvar(c("A" = 2), action = "suffix", Sys.getenv("A"))
)
#> [1] "1 2"
These functions are variants of the corresponding with_()
function,
but rather than resetting the value at the end of the function call they
reset when the current context goes out of scope. This is most useful
for using within functions.
f <- function(x) {
local_envvar(c("WITHR" = 2))
Sys.getenv("WITHR")
}
Sys.getenv("WITHR")
#> [1] ""