Skip to content

Defining generic methods for suggested packages #573

Closed

Description

@jtlandis

Hello everyone,

When building a package that is exporting a generic function, what is the proper way to export a method for a class within a "Suggests" package?

For example, if package foo exports the foo() generic, but lists package bar as a Suggests, what would be the proper way to register methods for classes within bar?

Would it be something to the effect of:

# from the foo package
.onLoad <- function(lib, pkg) {

  if (isNamespaceLoaded("bar")) {
    method(foo, bar::class_bar) <- function(x) {cat("we dispatched on `bar::class_bar`")}
  } else {
    setHook(packageEvent("bar", "onLoad"), function(){
      method(foo, bar::class_bar) <- function(x) {cat("we dispatched on `bar::class_bar`")}
    })
  }
}

Activity

  1. teunbrand commented on Oct 14, 2025

    @teunbrand
  2. jtlandis commented on Oct 14, 2025

    @jtlandis
    ContributorAuthor

    This is not quite what I am looking for and a bit opposite for my use case.

    The link describes how to conditionally register external generics for classes within your own package.

    For my use case, the foo generic exists in my own package I want to conditionally provide a method for an external class bar depending on if it is loaded or may get loaded in the future.

  3. hadley commented on Oct 15, 2025

    @hadley
    Member

    I think your approach with onLoad is reasonable, until we come up with something better. Just one thing to note is that you should call the setHook() unconditionally; this protects from (the admittedly rare case) where the user unloads then reload the package. I'd also extract out a function to reduce the duplication:

    register_bar <- function() {
      method(foo, bar::class_bar) <- function(x) {
        cat("we dispatched on `foo_bar`")
      }
    }
    
    .onLoad <- function(lib, pkg) {
      if (isNamespaceLoaded("bar")) {
        register_bar()
      }
      setHook(packageEvent("bar", "onLoad"), register_bar())
    }
  4. jtlandis commented on Oct 15, 2025

    @jtlandis
    Author
  5. hadley commented on Oct 15, 2025

    @hadley
  6. added
    feature
    on May 21, 2026
  7. added a commit that references this issue on Oct 2, 2026
    2662c59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureregistration 📓

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions