Skip to content

Odd behavior of symbol objects with classes/attributes

4 messages · Winston Chang, Duncan Murdoch, Luke Tierney

#
I've been trying to add classes and attributes to symbol objects
(created with quote()), and the behavior is very strange, as
illustrated in the examples below.

If symbols aren't meant to have classes and attributes attached to
them, then perhaps R should throw errors when you attempt to do it?


# Using str() strips class from object
x <- quote(foo)
class(x) <- "bar"
str(x)
# Class 'bar'  symbol foo
str(x)
# symbol foo


# Attempting to overwrite doesn't affect class.
# str() still strips class from the object.
x <- quote(foo)
class(x) <- "bar"
x <- quote(foo)
str(x)
# Class 'bar'  symbol foo
str(x)
# symbol foo


# Changing class of one object affects other
x <- quote(foo)
y <- quote(foo)
class(x) <- "bar"
class(y)
# [1] "bar"
str(y)
# Class 'bar'  symbol foo
str(y)
# symbol foo
str(x)
# symbol foo


# Changing attribute of one object affects other
# Unlike with class, str() doesn't cause other attributes to disappear
x <- quote(foo)
y <- quote(foo)
attr(x, "a") <- "bar"
str(y)
# length 1 foo
# - attr(*, "a")= chr "bar"
str(y)
# length 1 foo
# - attr(*, "a")= chr "bar"
str(quote(foo))
# length 1 foo
# - attr(*, "a")= chr "bar"


-Winston
#
On 17/06/2013 1:01 PM, Winston Chang wrote:
I think this is a consequence of another strange property of symbol 
objects, namely that they are not copied on assignment.  This is also 
true of environments, NULL, builtin function references, and some rarely 
encountered types like external pointers and weak references.  You're 
allowed to assign attributes to all of these other than NULL, but you 
will find strange things happen if you do it (as demonstrated in your 
code below).

I thought I remembered reading a list of these in the documentation 
somewhere, but when I went to look for it just now, I couldn't find it.  
(Maybe I'm remembering a comment in the source.)  It would be a useful 
addition.

Duncan Murdoch
#
On Mon, 17 Jun 2013, Duncan Murdoch wrote:

            
You are only because we haven't yet gotten around to preventing it --
we will at some point. For now, just don't try to assign attributes to
symbols.

Best,

luke

  
    
#
Thanks for the feedback, that clears things up.

-Winston
On Mon, Jun 17, 2013 at 1:29 PM, <luke-tierney at uiowa.edu> wrote: