[Rd] problem with print.generic(x)deparse(substitute(x))

peter dalgaard pdalgd at gmail.com
Mon Jan 9 11:24:15 CET 2017


On 09 Jan 2017, at 10:53 , Spencer Graves <spencer.graves at prodsyse.com> wrote:

> # Define an object of class 'dum'
> k <- 1
> class(k) <- 'dum'
> str(k) # as expected
> 
> # Define print.dum
> print.dum <- function(x, ...)
>  deparse(substitute(x))
> 
> print(k) # Prints "k" as expected
> #####**** THE FOLLOWING PRINTS NOTHING:
> k # Why?


Because it doesn't work that way...

First of all, your print.dum relies on autoprinting of its return value, it doesn't print anything itself. That's not how one usually writes print methods: You should print something and (usually) return the argument invisibly. 

Autoprinting calls the print method to do the actual printing and returns the object invisibly, irrespective of the return value from the print method. To wit:

> k
> dput(.Last.value)
structure(1, class = "dum")

(Trying to print the return value would invite infinite looping.)

However, there's another catch: deparse(substitute(...)) relies on knowing the argument to print() before evaluation, but autoprinting does not retain that information, it just looks at the object that has been computed and passes it to the relevant print method, so you get this effect:

> print.dum <- function(x, ...)
+  print(deparse(substitute(x)))
> k
[1] "x"

-pd



-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-devel mailing list