[R-pkg-devel] using a class from a suggested package

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Wed Feb 9 10:45:05 CET 2022


On Mon, 7 Feb 2022 15:55:18 +0100
Thierry Onkelinx <thierry.onkelinx using inbo.be> wrote:

> My package A defines an S4 method for the "inla" S3 class. The INLA
> package defines this class. That package has a huge source, making
> the build fail on r-universe.dev. The solution is to not
> importClassesFrom(INLA, inla) but use setOldClass("inla"). Then I can
> list INLA under Suggests instead of Imports. So far so good.

This is a really complicated situation to be in.

On the one hand, the only documented way to use S4 classes from another
package is NAMESPACE and importClassesFrom(), which leads to stronger
dependencies than you would like. On the other hand, you're likely to
get warnings if more than one loaded namespace define S4 classes with
the same name, to it's a good idea to avoid calling setOldClass('inla')
in the A package if INLA can be loaded.

Could it be an option to define the "maybeInla" class in the A package,
initially as "NULL", and then extend it at runtime using getClassDef?

setClassUnion('maybeInla', 'NULL')

.onLoad <- function(...) {
# ...
 if (requireNamespace('INLA', quietly = TRUE)) {
  setIs(getClassDef('inla', package = 'INLA'), 'maybeInla')
 }
# ...
}

If INLA can't be loaded, then there's (ostensibly) no way to create
"inla" objects in the current session, and "NULL" is as good a
definition as it would get. Then B could import the maybeInla class
from A.

-- 
Best regards,
Ivan



More information about the R-package-devel mailing list