From wo||g@ng@v|echtb@uer @end|ng |rom m@@@tr|chtun|ver@|ty@n|  Tue May 12 21:13:01 2020
From: wo||g@ng@v|echtb@uer @end|ng |rom m@@@tr|chtun|ver@|ty@n| (Viechtbauer, Wolfgang (SP))
Date: Tue, 12 May 2020 19:13:01 +0000
Subject: [Rd] S3 method dispatch for methods in local environments
In-Reply-To: <24250.62315.82219.364840@stat.math.ethz.ch>
References: <eed0ec0eb8e647c49250eae4dc9570db@UM-MAIL3214.unimaas.nl>
 <24250.62315.82219.364840@stat.math.ethz.ch>
Message-ID: <e830a1384d1940acacc370178464e9ac@UM-MAIL3214.unimaas.nl>

Indeed, that works:

myfun <- function(y) {
   out <- list(y=y)
   class(out) <- "myclass"
   return(out)
}

myenv <- new.env()
myenv$print.myclass <- local(function(x, ...) print(formatC(x$y, format="f", digits=5)), new.env(myenv))
.S3method("print", "myclass", myenv$print.myclass)
attach(myenv)
myfun(1:4)

# [1] "1.00000" "2.00000" "3.00000" "4.00000"

Thanks for the tip!

Best,
Wolfgang

>-----Original Message-----
>From: Martin Maechler [mailto:maechler at stat.math.ethz.ch]
>Sent: Tuesday, 12 May, 2020 21:05
>To: Viechtbauer, Wolfgang (SP)
>Cc: r-devel (r-devel at r-project.org)
>Subject: Re: [Rd] S3 method dispatch for methods in local environments
>
>>>>>> Viechtbauer, Wolfgang (SP)
>>>>>>     on Tue, 12 May 2020 18:05:32 +0000 writes:
>
>    > Dear All,
>    > In R 3.6.3 (and earlier), method dispatch used to work for methods
>stored in local environments that are attached to the search path. For
>example:
>
>    > myfun <- function(y) {
>    > out <- list(y=y)
>    > class(out) <- "myclass"
>    > return(out)
>    > }
>
>    > print.myclass <- function(x, ...) print(formatC(x$y, format="f",
>digits=5))
>
>    > myfun(1:4)
>
>    > # prints: [1] "1.00000" "2.00000" "3.00000" "4.00000"
>
>    > rm(print.myclass)
>    > myenv <- new.env()
>    > myenv$print.myclass <- local(function(x, ...) print(formatC(x$y,
>format="f", digits=5)), myenv)
>    > attach(myenv)
>    > myfun(1:4)
>
>    > # still prints: [1] "1.00000" "2.00000" "3.00000" "4.00000"
>
>    > But since R 4.0.0, this no longer words and the above prints:
>
>    > $y
>    > [1] 1 2 3 4
>
>    > attr(,"class")
>    > [1] "myclass"
>
>    > Is this intended?
>
>yes, most probably, unless
>
>    > And is there a way to still make this work?
>
>Using  the new
>
>       .S3method(<generic>, <class>, <method_function>)
>
>had been intended as substitute.  Can you try it with your
>attached-environment (which makes sense!)  approach ?
>
>Best,
>Martin



[Rd] S3 method dispatch for methods in local environments
Viechtbauer, Wolfgang (SP