Debian Codegraph @

inst/doc/withr.Rmd

raw
1 ---
2 title: "Changing and restoring state"
3 output: rmarkdown::html_vignette
4 vignette: >
5 %\VignetteIndexEntry{Changing and restoring state}
6 %\VignetteEngine{knitr::rmarkdown}
7 %\VignetteEncoding{UTF-8}
8 ---
9
10 ```{r, include = FALSE}
11 knitr::opts_chunk$set(
12 collapse = TRUE,
13 comment = "#>"
14 )
15 ```
16
17 ```{r setup}
18 library(withr)
19 ```
20
21 <!-- This vignette uses a git-diff-friendly convention of ONE LINE PER SENTENCE. -->
22
23 This article explains the type of problem withr solves and shows typical patterns of usage.
24 It also compares withr's functionality to the `on.exit()` function from base R.
25
26 ## It's dangerous to change state
27
28 Whenever possible, it is desirable to write so-called **pure** functions.
29 The property we focus on here is that the function should not change the surrounding R landscape, i.e. it should not change things like the search path, global options, or the working directory.
30 If the behaviour of *other* functions differs before and after running your function, you've modified the landscape.
31 Changing the landscape is bad because it makes code much harder to understand.
32
33 Here's a `sloppy()` function that prints a number with a specific number of significant digits, by adjusting R's global "digits" option.
34
35 ```{r include = FALSE}
36 op <- options()
37 ```
38
39 ```{r}
40 sloppy <- function(x, sig_digits) {
41 options(digits = sig_digits)
42 print(x)
43 }
44
45 pi
46
47 sloppy(pi, 2)
48
49 pi
50 ```
51
52 ```{r include = FALSE}
53 options(op)
54 ```
55
56 Notice how `pi` prints differently before and after the call to `sloppy()`?
57 Calling `sloppy()` has a side effect: it changes the "digits" option globally, not just within its own scope of operations.
58 This is what we want to avoid.
59
60 *Don't worry, we're restoring global state (specifically, the "digits" option) behind the scenes here.*
61
62 Sometimes you cannot avoid modifying the state of the world, in which case you just have to make sure that you put things back the way you found them.
63 This is what the withr package is for.
64
65 ## The base solution: `on.exit()`
66
67 The first function to know about is base R's `on.exit()`.
68 Inside your function body, every time you do something that should be undone **on exit**, you immediately register the cleanup code with `on.exit(expr, add = TRUE)`[^on-exit-add].
69
70 [^on-exit-add]: It's too bad `add = TRUE` isn't the default, because you almost always want this. Without it, each call to `on.exit()` clobbers the effect of previous calls.
71
72 `neat()` is an improvement over `sloppy()`, because it uses `on.exit()` to ensure that the "digits" option is restored to its original value.
73
74 ```{r}
75 neat <- function(x, sig_digits) {
76 op <- options(digits = sig_digits)
77 on.exit(options(op), add = TRUE)
78 print(x)
79 }
80
81 pi
82
83 neat(pi, 2)
84
85 pi
86 ```
87
88 `on.exit()` also works when you exit the function abnormally, i.e. due to error.
89 This is why official tools, like `on.exit()`, are a better choice than any do-it-yourself solution to this problem.
90
91 `on.exit()` is a very useful function, but it's not very flexible.
92 The withr package provides an extensible `on.exit()`-inspired toolkit.
93
94 ## `defer()` is the foundation of withr
95
96 `defer()` is the core function of withr and is very much like `on.exit()`, i.e. it schedules the execution of arbitrary code when the current function exits:
97
98 ```{r}
99 neater <- function(x, sig_digits) {
100 op <- options(digits = sig_digits)
101 defer(options(op))
102 print(x)
103 }
104
105 pi
106
107 neater(pi, 2)
108
109 pi
110 ```
111
112 `withr::defer()` is basically a drop-in substitute for `on.exit()`, but with three key differences we explore below:
113
114 1. Different default behaviour around the effect of a series of two or more
115 calls
116 1. Control over the environment the deferred events are associated with
117 1. Ability to work with the global environment
118
119 Here we focus on using withr inside your functions.
120 See the blog post [Self-cleaning test fixtures](https://tidyverse.org/blog/2020/04/self-cleaning-test-fixtures/) or the testthat vignette [Test fixtures](https://testthat.r-lib.org/articles/test-fixtures.html) for how to use withr inside tests.
121
122 ## Last-in, first-out
123
124 If you make more than one call to `defer()`, by default, it **adds** expressions to the **top** of the stack of deferred actions.
125
126 ```{r}
127 defer_stack <- function() {
128 cat("put on socks\n")
129 defer(cat("take off socks\n"))
130
131 cat("put on shoes\n")
132 defer(cat("take off shoes\n"))
133 }
134 defer_stack()
135 ```
136
137 In contrast, by default, a subsequent call to `on.exit()` **overwrites** the deferred actions registered in the previous call.
138
139 ```{r}
140 on_exit_last_one_wins <- function() {
141 cat("put on socks\n")
142 on.exit(cat("take off socks\n"))
143
144 cat("put on shoes\n")
145 on.exit(cat("take off shoes\n"))
146 }
147 on_exit_last_one_wins()
148 ```
149
150 Oops, we still have our socks on!
151 The last-in, first-out, stack-like behaviour of `defer()` tends to be what you want in most applications.
152
153 To get such behaviour with `on.exit()`, remember to call it with `add = TRUE, after = FALSE`[^on-exit-after].
154
155 [^on-exit-after]: Note: the `after` argument of `on.exit()` first appeared in R 3.5.0.
156
157 ```{r, eval = getRversion() >= "3.5.0"}
158 on_exit_stack <- function() {
159 cat("put on socks\n")
160 on.exit(cat("take off socks\n"), add = TRUE, after = FALSE)
161
162 cat("put on shoes\n")
163 on.exit(cat("take off shoes\n"), add = TRUE, after = FALSE)
164 }
165 on_exit_stack()
166 ```
167
168 Conversely, if you want `defer()` to have first-in, first-out behaviour, specify `priority = "last"`.
169
170 ```{r}
171 defer_queue <- function() {
172 cat("Adam gets in line for ice cream\n")
173 defer(cat("Adam gets ice cream\n"), priority = "last")
174
175 cat("Beth gets in line for ice cream\n")
176 defer(cat("Beth gets ice cream\n"), priority = "last")
177 }
178 defer_queue()
179 ```
180
181 ## "Local" functions (and "with" functions)
182
183 Both `on.exit()` and `withr::defer()` schedule actions to be executed when a certain environment goes out of scope, most typically the execution environment of a function.
184 But the `envir` argument of `withr::defer()` lets you specify a *different* environment, which makes it possible to create customised `on.exit()` extensions.
185
186 Let's look at the `neater()` function again.
187
188 ```{r}
189 neater <- function(x, sig_digits) {
190 op <- options(digits = sig_digits) # record orig. "digits" & change "digits"
191 defer(options(op)) # schedule restoration of "digits"
192
193 print(x)
194 }
195 ```
196
197 The first two lines are typical `on.exit()` maneuvers where, in some order, you record an original state, arrange for its eventual restoration, and
198 change it.
199 In real life, this can be much more involved and you might want to wrap this logic up into a helper function.
200 You can't wrap `on.exit()` in this way, because there's no way to reach back up into the correct parent frame and schedule cleanup there.
201 But with `defer()`, we can!
202 Here is such a custom helper, called `local_digits()`.
203
204 ```{r}
205 local_digits <- function(sig_digits, envir = parent.frame()) {
206 op <- options(digits = sig_digits)
207 defer(options(op), envir = envir)
208 }
209 ```
210
211 We can use `local_digits()` to keep any manipulation of `digits` local to a function.
212
213 ```{r}
214 neato <- function(x, digits) {
215 local_digits(digits)
216 print(x)
217 }
218
219 pi
220
221 neato(pi, 2)
222
223 neato(pi, 4)
224 ```
225
226 You can even call `local_digits()` multiple times inside a function.
227 Each call to `local_digits()` is in effect until the next or until the function exits, which ever comes first.
228
229 ```{r}
230 neatful <- function(x) {
231 local_digits(1)
232 print(x)
233 local_digits(3)
234 print(x)
235 local_digits(5)
236 print(x)
237 }
238
239 neatful(pi)
240 ```
241
242 Certain state changes, such as modifying global options, come up so often that withr offers pre-made helpers.
243 These helpers come in two forms: `local_*()` functions, like the one we just made, and `with_*()` functions, which we explain below.
244 Here are the state change helpers in withr that you are most likely to find useful:
245
246 | Do / undo this | withr functions |
247 |-----------------------------|-------------------------------------|
248 | Set an R option | `local_options()`,`with_options()` |
249 | Set an environment variable | `local_envvar()`, `with_envvar()` |
250 | Change working directory | `local_dir()`, `with_dir()` |
251 | Set a graphics parameter | `local_par()`, `with_par()` |
252
253 We didn't really need to write our own `local_digits()` helper, because the built-in `withr::local_options()` also gets the job done:
254
255 ```{r}
256 neatest <- function(x, sig_digits) {
257 local_options(list(digits = sig_digits))
258 print(x)
259 }
260
261 pi
262
263 neatest(pi, 2)
264
265 neatest(pi, 4)
266 ```
267
268 The `local_*()` functions target a slightly different use case from the `with_*()` functions, which are inspired by base R's `with()` function:
269
270 * `with_*()` functions are best for executing a small snippet of code with a
271 modified state
272 ```{r eval = FALSE}
273 neat_with <- function(x, sig_digits) {
274 # imagine lots of code here
275 withr::with_options(
276 list(digits = sig_digits),
277 print(x)
278 )
279 # ... and a lot more code here
280 }
281 ```
282 * `local_*()` functions are best for modifying state "from now until the
283 function exits"
284 ```{r eval = FALSE}
285 neat_local <- function(x, sig_digits) {
286 withr::local_options(list(digits = sig_digits))
287 print(x)
288 # imagine lots of code here
289 }
290 ```
291
292 It's best to minimize the footprint of your state modifications.
293 Therefore, use `with_*()` functions where you can.
294 But when this forces you to put lots of (indented) code inside `with_*()`, e.g. most of your function's body, then it's better to use `local_*()`.
295
296 ## Deferring events on the global environment
297
298 Here is one last difference between `withr::defer()` and `on.exit()`: the ability to defer events on the global environment[^withr-2-2-0].
299
300 [^withr-2-2-0]: This feature first appeared in withr v2.2.0.
301
302 At first, it sounds pretty weird to propose scheduling deferred actions on the global environment.
303 It's not ephemeral, the way function execution environments are.
304 It goes out of scope very rarely, i.e. when you exit R.
305 Why would you want this?
306
307 The answer is: for development purposes.
308
309 If you are developing functions or tests that use withr, it's very useful to be able to execute that code interactively, without error, and with the ability to trigger the deferred events.
310 It's hard to develop with functions that work one way inside a function, but another way in the global environment (or, worse, throw an error).
311
312 Here's how `defer()` (and all functions based on it) works in an interactive session.
313
314 ```{r}
315 library(withr)
316
317 defer(print("hi"))
318
319 pi
320
321 # this adds another deferred event, but does not re-message
322 local_digits(3)
323
324 pi
325
326 deferred_run()
327
328 pi
329 ```
330
331 Note that because this example is running in a vignette, it doesn't look exactly the same as what you'll see interactively. When you defer events on the global environment for the first time, you get this message that alerts you to the situation:
332
333 ```{r, eval = FALSE}
334 defer(print("hi"))
335 #> Setting global deferred event(s).
336 #> i These will be run:
337 #> * Automatically, when the R session ends.
338 #> * On demand, if you call `withr::deferred_run()`.
339 #> i Use `withr::deferred_clear()` to clear them without executing.
340 ```
341
342 If you add subsequent events, the message is *not* repeated.
343 Since the global environment isn't perishable, like a test environment is, you have to call `deferred_run()` explicitly to execute the deferred events. You can also clear them, without running, with `deferred_clear()`.