Skip to content

Ensure Ops falls back to base behaviour - #382

Merged
hadley merged 6 commits into
mainfrom
ops-default
Nov 30, 2023
Merged

hadley merged 6 commits into
mainfrom
ops-default

Conversation

@hadley

@hadley hadley commented Nov 23, 2023 •

Copy link
Copy Markdown
Member

Fixes #320

I also tried this:

chooseOpsMethod.S7_object <- function(x, y, mx, my, cl, reverse) {
  S7_inherits(x) && S7_inherits(y)
}

But that leaves us with (e.g.) incompatible methods ("Ops.S7_object", "Ops.factor") for "+".

Comment thread R/method-dispatch.R Resolved
Comment thread R/method-ops.R
Comment on lines +19 to +22
cnd <- tryCatch(
return(base_ops[[.Generic]](e1, e2)),
methodNotFound = function(cnd) cnd
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to think of any other way to do this to avoid the non-negligible performance hit of tryCatch(), but I can't really think of one:

  • We don't have an easy to do findMethod(.Generic, e1 = e1, e2 = e2) so we can't try looking it up without calling it
  • I don't think we can easily use the more performant withCallingHandlers() without more effort, since we don't always rethrow the error

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given the general cost of dispatch I'm not sure this is worth worrying too much about?

library(S7)

foo <- new_class("foo")
method(`+`, list(foo, foo)) <- function(e1, e2) 100
f <- foo()

bench::mark(
  f + f,
  tryCatch(f + f)
)
#> # A tibble: 2 × 6
#>   expression           min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>      <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 f + f             5.21µs   5.78µs   167089.    39.9KB     50.1
#> 2 tryCatch(f + f)   6.76µs   7.42µs   132355.    12.4KB     53.0

Created on 2023-11-29 with reprex v2.0.2.9000

Comment thread tests/testthat/test-method-ops.R Resolved
@hadley
hadley merged commit 2cec150 into main Nov 30, 2023
@hadley
hadley deleted the ops-default branch November 30, 2023 13:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

base_ops are empty - arithmetic fails e.g. when extending class_double

2 participants