Getting the object name for S3 print method failing

701 views Asked by At

Define an object of S3 class "bar" and a print method:

foo=list(1)
class(foo) <- c("bar")
print.bar <- function(x,...){
  cat("print.bar says this was ",deparse(substitute(x)),"\n")
}

Now print(foo) does this:

> print(foo)
print.bar says this was  foo 

Great, but auto-printing fails:

> foo
print.bar says this was  structure(list(1), class = "bar")

I'm guessing this is something to do with the way the line is evaluated as a top-level expression. Had a quick search on R-devel to no avail. Anyone know how to fix it?

The reason I want the name is because the thing I am defining is a function, and I want to be able to put 'try foo(2)' in the print method (getting 'foo' from the name of the object). Yes, you can subclass functions in S3. I suppose there may be other pifalls..

2

There are 2 answers

1
Joris Meys On BEST ANSWER

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. This can be illustrated by :

foo=list(1)
class(foo) <- c("bar")
print.bar <- function(x,...){
  print(sys.calls())
}

> foo
[[1]]
print(list(1))

[[2]]
print.bar(list(1))

> print(foo)
[[1]]
print(foo)

[[2]]
print.bar(foo)

ergo, without the name as an attribute (like Aaron showed), there is no way on earth you'll extract the name of the object from anywhere. It's simply not there in the callstack.

0
Aaron left Stack Overflow On

If you're not going to be renaming the object, you could include the name as an attribute and print that instead.

foo <- structure(list(1), class="bar", name="foo")
print.bar <- function(x,...){
  cat("print.bar says this was",attr(x, "name"),"\n")
}

Then it does what you expect:

> print(foo)
print.bar says this was foo 
> foo
print.bar says this was foo 

Unless you use a different name for the same object:

> fooX <- foo
> fooX
print.bar says this was foo