Skip to content

addTaskCallback(..., on = c("exit", "enter")): Add support for callback function before evaluation #107

@HenrikBengtsson

Description

@HenrikBengtsson

Background

We can use addTaskCallback() to register "an R function that is to be called each time a top-level task is completed". For example, with:

addTaskCallback(function(expr, value, ok, visible) {
  message("Top-level task completed:")
  utils::str(list(expr = expr, value = value, ok = ok, visible = visible))
  TRUE
})

we get:

> 1+2
[1] 3
Top-level task completed:
List of 4
 $ expr   : language 1 + 2
 $ value  : num 3
 $ ok     : logi TRUE
 $ visible: logi TRUE

> sample(1:10)
 [1]  7  8 10  4  2  3  1  5  9  6
Top-level task completed:
List of 4
 $ expr   : language sample(1:10)
 $ value  : int [1:10] 7 8 10 4 2 3 1 5 9 6
 $ ok     : logi TRUE
 $ visible: logi TRUE

Wish

Make it possible to register a function that is called before the expression is evaluated, e.g.

addTaskCallback(function(expr) {
  message("Top-level task about to be called:")
  utils::str(list(expr = expr))
  TRUE
}, on = "enter")

which, with the previously registered callback, would give:

> 1+2
Top-level task about to be called:
List of 1
 $ expr   : language 1 + 2
[1] 3
Top-level task completed:
List of 4
 $ expr   : language 1 + 2
 $ value  : num 3
 $ ok     : logi TRUE
 $ visible: logi TRUE

The default should be on = "exit" for backward compatible reasons.

Motivation

This would open up for various types of profiling, e.g. time and memory consumption for different type of tasks. It would also allow to pre-inspect calls before they are made, e.g. assisting users and help them avoid common mistakes.

Example

Time evaluations at the R prompt:

t_start <- NULL

addTaskCallback(function(expr) {
  globalenv()$t_start <- proc.time()
  }, on = "enter")

addTaskCallback(function(expr) {
  duration <- proc.time() <- globalenv()$t_start
  message(sprintf("Ellapsed time: %g s", duration))
}, on = "enter")

gives:

> Sys.time(2.5)
Ellapsed time: 2.5 s

>

Discussion

It could be discussed whether the on = "enter" callback function should be able to modify the expression expr before the task is evaluated. I can imagine this could become a feature request in the future.

See also

Metadata

Metadata

Assignees

No one assigned

    Labels

    CIssues requiring knowledge of CuseR! 2025Issues reserved for R Dev Day @ useR! 2025

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions