From spinuvit.list at gmail.com  Sun Aug 15 23:39:15 2010
From: spinuvit.list at gmail.com (Vitaly S.)
Date: Sun, 15 Aug 2010 23:39:15 +0200
Subject: [Rd] parent.frame(1) of a S4 method is not a calling environment.
Message-ID: <87d3tj4ku4.fsf@gmail.com>


Dear Developers,

I wonder what are the parent.frame rules for methods. For ordinary functions one
can call parent.frame() and be sure that it is the environment of a calling
function. With S4 aparently it is not the case.

Here is what I have discovered by trial and error so far:

> setClass("A", contains="vector")
[1] "A"
> setGeneric("foo", def=function(a, ...){standardGeneric("foo")})
[1] "foo"
> 
> setMethod("foo", signature("A"), 
+           def=function(a, ...){
+             cat("--pf1--\n")
+             ls(parent.frame(1))
+             ## cat("--pf2--")
+             ## ls(parent.frame(2))
+           })
[1] "foo"
> 
> tf <- function(){
+   b <- 4
+   foo(new("A")) #ok
+ }
> 
> tf() #ok
--pf1--
[1] "b"

The above works like predicted.
Now, a small change. The "b" argument which is not in the signature, but has a
role of an additional parameter to the function:

> setMethod("foo", signature("A"), 
+           def=function(a, b, ...){
+             cat("--pf1--\n")
+             print(ls(parent.frame(1)))
+             cat("--pf2--\n")
+             print(ls(parent.frame(2)))
+           })
[1] "foo"
> 
> tf()  #oups
--pf1--
[1] "a"
--pf2--
[1] "b"
> 

So,  can I be sure that for such functions parent.frame(2) will always work?
What are the additional rules?

Many thanks,
Vitaly.



[Rd] parent.frame(1) of a S4 method is not a calling environment.
Vitaly S.