Debugging methods in R6 classes is somewhat different from debugging normal R functions.
RStudio breakpoints don’t work in R6 class methods. The simplest way
to debug code is to insert a browser() line where you want
to open a debugging console, reload the classes, and then step through
your code. But this involves modifying your code, reloading it, and
re-instantiating any objects you want to test.
Enabling debugging for all future instances of a class
R6 generator objects have a method called debug() which
will enable debugging for a method. This will affect all instances of
the class that are created after the debug() is called.
# An example class
Simple <- R6Class("Simple",
public = list(
x = 10,
getx = function() self$x
)
)
# This will enable debugging the getx() method for objects of the 'Simple'
# class that are instantiated in the future.
Simple$debug("getx")
s <- Simple$new()
s$getx()
# [Debugging prompt]To disable debugging for future instances, use the generator’s
undebug() method:
# Disable debugging for future instances:
Simple$undebug("getx")
s <- Simple$new()
s$getx()
#> [1] 10Debugging methods in individual objects
To enable debugging for a method in a single instance of an object,
use the debug() function (not the debug()
method in the generator object).
s <- Simple$new()
debug(s$getx)
s$getx()
# [Debugging prompt]Use undebug() to disable debugging on an object’s
method.
undebug(s$getx)
s$getx()
#> [1] 10You can also use the trace() function to specify where
in a method you want to drop into the debugging console.