r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
489 stars 131 forks source link

Document `caller_arg()` limitation in `print()` #1690

Closed DanChaltiel closed 1 month ago

DanChaltiel commented 4 months ago

Hi,

I stumbled upon the caller_arg() limitation when redefining a print method for hours without understanding, and thought it might deserve a bit of documentation.

As stated in https://stackoverflow.com/a/4963041/3888000:

This is a rather special case, as R substitutes foo by its value before calling print when you type the name at the command line. [...] There is no way on earth you'll extract the name of the object from anywhere. It's simply not there in the callstack.

Here is a rlang specific reprex:

my_obj=1
class(my_obj)="bar"
print.bar = function(x) rlang::caller_arg(x)
mean.bar = function(x) rlang::caller_arg(x)
my_obj
#> x
mean(my_obj)
#> [1] "my_obj"

#however, this works as intended
print(my_obj)
#> [1] "my_obj"

Created on 2024-02-21 with reprex v2.0.2

lionel- commented 1 month ago

Thank you, unfortunately I think that this is a sufficiently specific edge case that this section would not be very helpful.

I'd welcome a PR adding a section that speaks more generally about the caveats of caller-arg/substitute in contexts where the argument might be inlined in the call stack. Print and auto-print could be used as an example to show the difference. This section would need to be pedagogical about the concepts involved while being sufficiently succinct that it does not take up too much space in the documentation.

DanChaltiel commented 1 month ago

It is quite understandable. Unfortunately, I'm afraid I'm not expert enough on the call stack to be pedagogical about it.