[R-pkg-devel] S3 length method behavior

Hadley Wickham h.wickham at gmail.com
Tue Feb 2 16:28:48 CET 2016


I've found that it's a very bad idea to provide length or names
methods for just this reason.
Hadley

On Sat, Jan 30, 2016 at 1:25 PM, Nathan Wendt <nawendt84 at gmail.com> wrote:
> Hello,
>
> I have run into an issue while developing an R package. Specifically, my
> issue relates to what happens when I define an S3 length method for my
> class. Here is my basic setup:
>
> # Here is the structure of myClass
> # uses an externalptr to operate on file using some C functions
> list(file = "my/file/location", handle = <externalptr>)
>
> # this function gets an S3Method() in NAMESPACE
> length.myClass <- function(x) {
>   .Call("get_class_length",myPkg)
> }
>
> As you can see, myClass is just a list of two pieces of information about
> the particular object. Without a defined length method, length(myClass)
> would be 2. However, I defined a length method to give me the information
> about the amount of binary messages contained in the file the object points
> to. In one of my test files there are 82 messages and length(myObject)
> correctly returns 82. What I ran into is that I was crashing RStudio when
> rebuilding my package with an object of myClass in my environment. Only
> removing my S3 length method caused the crash to not occur. After looking
> for memory leaks and other errors I finally noticed that the str() on the
> object of myClass looked odd. It returned something like this:
>
> List of 82
>  $ file  : chr "my/file/location"
>  $ handle:<externalptr>
>  $ NA:
> Error in object[[i]] : subscript out of bounds
>
> It seems that when I define an S3 method for length that somehow the object
> of myClass then gets restructured to have the length returned by the
> function. There are 82 messages in the file, but myClass objects should
> only have two elements. My best guess here is that the RStudio crash was
> happening because the object was misrepresented internally. Of course, I
> cannot be sure. None of my tests pointed to anything useful.
>
> My questions are, then, whether this behavior makes sense and what to do
> about it. If I define my own str() method, will that fix it? I think I am
> just misunderstanding what is going on with the methods I have defined.
> Hopefully, someone can offer some clarity.
>
> Thanks,
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-package-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-package-devel



-- 
http://had.co.nz/



More information about the R-package-devel mailing list