0

I want to access compute_group() of the parent method within my own ggproto object. Here are two different working approaches, but don't know if any is the "correct" way to go:

  1. self$super()$compute_group(...)
  2. ggproto_parent(<parent>, self)$compute_group(...)

Any (strong) opinions?

moremo
  • 315
  • 2
  • 11

1 Answers1

1

I'm just here to suggest that the correct way to do it is to use your second approach. One reason is that the documentation of ?ggproto reads:

To explicitly call a methods in a parent, use ggproto_parent(Parent, self).

A second reason is that ggplot2 source code never uses self$super()$method(), from which you could deduce that it is not intended to be used that way.

A third option to consider is to call OtherClass$compute_group() directly in your code. This should work because the ggproto classes are designed to be stateless, so this should be safe if you adhere to the statelessness rule. The ggplot2 book mentions that this pattern in more prevalent than the ggproto_parent() method due to its clarity and equivalent safety.

teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • Thanks, indeed, all three options work! An advantage of using `OtherClass$compute_group()` is that no `self` argument is needed in the new "child" `ggproto` method anymore, a disadvantage might be that it's not that clear, that it is using the parent method. But perhaps the distinction between child and parent method is even no longer important? – moremo Oct 06 '21 at 07:53
  • Having re-read the section in the [ggplot2 book](https://ggplot2-book.org/internals.html#ggproto-classes-have-simple-inheritance), I would like to add the relevant paragraphs mentioned by @teunbrand here for clarity: "While we have seen that parent methods can be called using `ggproto_parent()` this pattern is quite rare to find in the `ggplot2` source code, as the pattern shown above is often clearer and just as safe." - referring to calling `OtherClass$method()`. – moremo Oct 19 '21 at 09:45