magrittr icon indicating copy to clipboard operation
magrittr copied to clipboard

Debugging a pipe with browser()

Open hadley opened this issue 7 years ago • 3 comments

Can we make this work?

100 %>% sample(10) %T>% browser() %>% sum()

The primary challenge is that the first argument to browser() is text.

hadley avatar Jul 02 '18 20:07 hadley

100 %>% sample(10) %T>% { browser() } %>% sum()

more useful in the proposal branch though.

smbache avatar Jul 02 '18 22:07 smbache

I know we want to minimise aliases, but maybe this would be useful enough to qualify for inclusion:

pipe_browser <- function(x, condition = NULL) {
  if (is.null(condition) || isTRUE(condition) {
    browser()
  }

  invisible(x)
}

(Edited to support conditional browsing)

hadley avatar Jul 03 '18 12:07 hadley

Ooops, except that we need to evaluate browser() in the caller_env()

library(rlang)

pipe_browser <- function(x, condition = NULL) {
  if (is.null(condition) || isTRUE(condition)) {
    eval_bare(expr(browser(skipCalls = 1L)), env = caller_env())
  }

  invisible(x)
}

# Check that it works
f <- function(x) {
  y <- 10
  pipe_browser(y)
}
f(1)

hadley avatar Jul 03 '18 12:07 hadley