Roxygen `@example` comparable to Python doctest?

roxygen2

#1

Is the @example in roxygen equivalent to a doctest in Python?

Is it intended to be used in the same way and what are potential differences?


#2

Assuming your uses of doctest in Python ~match up with those described here, which are summed up at the end as:

  1. Checking examples in docstrings.
  2. Regression testing.
  3. Executable documentation / literate testing.

there is some overlap. In the Writing R documentation files section of Writing R Extensions:

\examples{…}
Examples of how to use the function. Code in this section is set in typewriter font without reformatting and is run by example() unless marked otherwise (see below).

Examples are not only useful for documentation purposes, but also provide test code used for diagnostic checking of R code. By default, text inside \examples{} will be displayed in the output of the help page and run by example() and by R CMD check. You can use \dontrun{} for text that should only be shown, but not run, and \dontshow{} for extra commands for testing that should not be shown to users, but will be run by example().

As described in the Object Documentation section of R Packages:

@examples provides executable R code showing how to use the function in practice. This is a very important part of the documentation because many people look at the examples first. Example code must work without errors as it is run automatically as part of R CMD check.

So, like doctest, yes, they are a sort of executable documentation and serve as a test of sorts (presuming you don't exclude the example from running by putting \dontrun{}).

I'm not that familiar with doctest, but roxygen examples are certainly intended to be illustrative of basic functionality for your package/functions. So, the more testing-oriented sections of the doctest docs sound closer to the equivalent of straight-up tests (see Testing section of R Packages).

The "Advanced API" functionality in doctests (as depicted in the diagram below) doesn't (to my knowledge) have an @examples equivalent.

                           list of:
+------+                   +---------+
|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
+------+    |        ^     +---------+     |       ^    (printed)
            |        |     | Example |     |       |
            v        |     |   ...   |     v       |
           DocTestParser   | Example |   OutputChecker
                           +---------+

Hope this helps.


#3

Hi Mara, thank you so much for your comprehensive answer. It made things a lot clearer to me and is very helpful.


#4

5 posts were split to a new topic: I am familiar with doctest. I am not familiar with Roxygen.