RConsortium / S7

S7: a new OO system for R
https://rconsortium.github.io/S7
Other
399 stars 33 forks source link

Functions to list classes/generics in a package #335

Open hadley opened 1 year ago

hadley commented 1 year ago

And to list all S7 methods for a S3/S4 generic.

Extracted from #333.

cc @mmaechler do you have any additional thoughts about what sort of API you'd like here? I'm not familiar with the S4 equivalents.

mmaechler commented 1 year ago

There (S4), we have e.g., getGenerics(where = asNamespace("Matrix")) or getClasses(where = ..) and we can e.g., ask for the "full game" via something like

length(Mgen <- getGenerics(asNamespace("Matrix"))) # |-> 113
Mmeth <- sapply(Mgen, findMethods)) 
  # |->  a named list with 113 components, each with all methods of the generic, the gen., signatures, ..

the camel case matches the general S4 naming scheme .. and is probably not what we want here, but the concept of providing "what is there" as (lists of ...) is useful for inspection, checking, etc.

hadley commented 1 year ago

Are these conceptually these filtered versions of ls()? i.e. the implementation of S7::find_generics() could be something like this?

find_generics <- function(pkg) {
  env <- asNamespace(pkg)
  Filter(function(nm) is_generic(get(nm, env)), ls(envir = env))
}
hadley commented 1 year ago

Some very initial API thoughts:

find_generics <- function(env) {
  env <- as.environment(env)
  Filter(function(nm) is_generic(get(nm, env)), ls(envir = env))
}

find_classes <- function(env) {
  env <- as.environment(env)
  Filter(function(nm) is_generic(get(nm, env)), ls(envir = env))
}

find_methods <- function(env) {
  if (is_generic(env)) {
    methods <- as.list(env@methods)  
  } else {
    env <- as.environment(env)
    attr(tbl[[".__S3MethodsTable__."]], "S7methods")
  }
}