Importing a package's S3 methods without importing its functions

I have the following dependency chain in a package I'm developing:

How do I use/import the S3 method without importing the rest of package B, preferably via roxygen2?

The roxygen2 documentation suggests the following:

If you want to add a new method to an S3 generic, import it with @importFrom pkg generic.

For my example, this would be @importFrom simmer.plot plot, but this returns a warning that plot is not exported by simmer.plot. The same thing happens if I import the generic first, using @importFrom graphics plot.

Upvotes: 4

Views: 457

Answers (2)

Iñaki Úcar
Iñaki Úcar

Reputation: 975

Use (see this):

#' @rawNamespace import(simmer, except=c(get_mon_arrivals, get_mon_resources, get_mon_attributes))
#' @import simmer.plot

because you really need to use the overloaded functions in simmer.plot so that the plot methods there can work. An equivalent, but shorter version:

#' @rawNamespace import(simmer, except=getNamespaceExports("simmer.plot"))
#' @import simmer.plot

Upvotes: 2

Iñaki Úcar's mention of the @rawNamespace tag led me to work out a version that doesn't import any of package B's exported functions, using the getNamespaceExports function mentioned in this answer:

#' @rawNamespace import(packageB, except = getNamespaceExports("packageB"))

The @rawNamespace tag in roxygen2 inserts raw code into the NAMESPACE file. getNamespaceExports returns the names of all exported functions in a namespace: this can be a package that you haven't attached.

For my specific example, I can write this:

#' @import simmer
#' @rawNamespace import(simmer.plot, except = getNamespaceExports("simmer.plot"))

which puts these lines in the NAMESPACE:

import(simmer)
import(simmer.plot, except = getNamespaceExports("simmer.plot"))

Upvotes: 2

Related Questions