Skip to content
Back to formatted view

Raw Message

Message-ID: <2476de02-2acf-b413-058f-9dd6981ff4a4@gmail.com>
Date: 2017-12-06T18:51:26Z
From: Duncan Murdoch
Subject: [R-pkg-devel] Conditionally register method with generic in other package
In-Reply-To: <D6A8DD57-F071-4D21-810D-45E88A9A07EB@denney.ws>

On 06/12/2017 8:44 AM, Bill Denney wrote:
> 
>> On Dec 6, 2017, at 07:45, Joshua Ulrich <josh.m.ulrich at gmail.com> wrote:
>>
>> To avoid excessive dependencies, I would like to only register
>> foo.bar() if package A is installed at the time package B is
>> installed.  If package A is installed after package B, then warn the
>> user when package B is loaded and/or attached, so they can re-install
>> A and have foo.bar() registered correctly.
> 
> One simple solution would be to wrap the instantiation of foo.bar in a require test:
> 
> if (require(A)) {
>    foo.bar <- function(...) {
>      print("To be or not to be")
>    }
> } else {
>    message("To use the foo.bar function, please install package A.")
> }
> 

It's usually better to use requireNamespace("A") instead of require("A") 
(and the quotes are needed in requireNamespace(), but optional in 
require()). That tries to load the package, but doesn't mess with the 
search list.

But that'll likely cause warnings, unless the same condition is used in 
the NAMESPACE file where there should be an entry

S3method(foo, bar)

The thing is, I'm not sure if

if (requireNamespace("A"))
   S3method(foo, bar)

is legal in a NAMESPACE file.

Duncan Murdoch