Вот что я придумала:
traceonce <- function(what, tracer, exit, at, print, signature,
where = topenv(parent.frame()), edit = FALSE){
mc <- match.call()
mc[[1]] <- quote(trace)
mc[["exit"]] <-
if (missing(exit)) substitute(quote(eval.parent(quote(untrace(what)))))
else c(as.expression(exit), substitute(eval.parent(quote(untrace(what)))))
eval.parent(mc)
}
Я редактирую формальности вызова, поэтому мне не нужно иметь дело с кучей проверок на missing
, затем я редактирую exit
элемент вызова (2 случая, существует или нет), чтобы добавить вызов для отслеживания данной функции.
С exit
аргумент:
traceonce(head, exit = quote({print("hello")}))
#> Tracing function "head" in package "utils"
#> [1] "head"
head(cars,1)
#> Tracing head(cars, 1) on exit
#> [1] "hello"
#> Untracing function "head" in package "utils"
#> speed dist
#> 1 4 2
head(cars,1)
#> speed dist
#> 1 4 2
Безexit
аргумент:
traceonce(head, quote({print("hello")}))
#> Tracing function "head" in package "utils"
#> [1] "head"
head(cars,1)
#> Tracing head(cars, 1) on entry
#> [1] "hello"
#> Tracing head(cars, 1) on exit
#> Untracing function "head" in package "utils"
#> speed dist
#> 1 4 2
head(cars,1)
#> speed dist
#> 1 4 2