rlang icon indicating copy to clipboard operation
rlang copied to clipboard

obj_type, obj_desc, and obj_friendly_type

Open hadley opened this issue 6 years ago • 4 comments

e.g.

obj_type(1:10)
#> int

obj_desc(1:10)
#> int [10]

obj_friendly_type(1:10)
#> an integer vector

hadley avatar Mar 12 '18 16:03 hadley

This would only use switchpatch. Needs to have C backend for use elsewhere in package (and eventually in exported API)

If this existed, I think pillar::type_sum.default() could use obj_type().

hadley avatar Mar 12 '18 16:03 hadley

See also pillar: https://github.com/r-lib/pillar/blob/master/R/type-sum.R

And I have this code in local ggplot2 branch:

obj_desc <- function(x) {
  if (isS4(x)) {
    paste0("an S4 object with class ", class(x)[[1]])
  } else if (is.object(x)) {
    if (is.data.frame(x)) {
      "a data frame"
    } else if (is.factor(x)) {
      "a factor"
    } else {
      paste0("an S3 object with class ", paste(class(x), collapse = "/"))
    }
  } else {
    switch(typeof(x),
      "NULL" = "a NULL",
      character = "a character vector",
      integer = "an integer vector",
      logical = "a logical vector",
      double = "a numeric vector",
      list = "a list",
      closure = "a function",
      paste0("a base object of type", typeof(x))
    )
  }
}

I don't think these functions should do dispatch, but they will have to handle S4 objects in a generic way.

hadley avatar Mar 12 '18 16:03 hadley

Adding cnd label, since this is related to making helpful error messages

hadley avatar May 07 '18 14:05 hadley

also need a way to obtain the friendly type without an indefinite article. Perhaps an argument?

obj_friendly_type(tibble())
#> [1] "a data frame"

obj_friendly_type(tibble(), article = FALSE)
#> [1] "data frame"

lionel- avatar Dec 07 '18 09:12 lionel-