From pdalgd at gmail.com  Mon Jan  9 11:24:15 2017
From: pdalgd at gmail.com (peter dalgaard)
Date: Mon, 9 Jan 2017 11:24:15 +0100
Subject: [Rd] problem with print.generic(x)deparse(substitute(x))
In-Reply-To: <f96d2039-6760-6cff-c42d-bda85015f7e0@prodsyse.com>
References: <f96d2039-6760-6cff-c42d-bda85015f7e0@prodsyse.com>
Message-ID: <0E4497A7-60AF-4804-8BD9-66836198A7AE@gmail.com>


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



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