From jmc at r-project.org  Fri Jul 16 18:47:26 2010
From: jmc at r-project.org (John Chambers)
Date: Fri, 16 Jul 2010 09:47:26 -0700
Subject: [Rd] Creating an environment with attributes in a package
In-Reply-To: <AANLkTimX45rQ_VXDNp5Vs0zkb7dMRv2_hOwRatS5GdOI@mail.gmail.com>
References: <AANLkTin3LINSssOpwJtqsUsW1Mt-1PH8h9eIiW7H4xny@mail.gmail.com>	<AANLkTinfhXQJCXuUSERSUfyBuncOZZdjLDnVDtPP-28a@mail.gmail.com>
	<AANLkTimX45rQ_VXDNp5Vs0zkb7dMRv2_hOwRatS5GdOI@mail.gmail.com>
Message-ID: <4C408D1E.8040902@r-project.org>

Note that S4 classes extend "environment" and other reference types, by 
using a hidden slot.  You can then add other slots.  So, with some extra 
work:

 > setClass("myEnv", contains = "environment",
+ representation(myName = "character"))
[1] "myEnv"
 > Foo <- new("myEnv", myName = "Foo")
 > Foo
An object of class "myEnv"
<environment: 0x101a3a580>
Slot "myName":
[1] "Foo"

There are a few holes in the implementation as of R 2.11.1, which are 
being filled in r-devel.  Partly to support some new applications for 
extensions of environments, which I hope to commit today (stay tuned to 
this list).


On 7/16/10 5:51 AM, Jon Clayden wrote:
> On 16 July 2010 13:32, Hadley Wickham<hadley at rice.edu>  wrote:
>> On Fri, Jul 16, 2010 at 2:08 PM, Jon Clayden<jon.clayden at gmail.com>  wrote:
>>> Dear all,
>>>
>>> I am trying to create an environment object with additional attributes, viz.
>>>
>>> Foo<- structure(new.env(), name="Foo")
>>>
>>> Doing this in a standard session works fine: I get the environment
>>> with attr(,"name") set as expected. But if the same code appears
>>> inside a package source file, I get just the plain environment with no
>>> attributes set. Using a non-environment object works as I would expect
>>> within the package (i.e. the attributes remain).
>>>
>>> I've looked through the documentation for reasons for this, and the
>>> only thing I've found is the mention in the language definition that
>>> "assigning attributes to an environment can lead to surprises". I'm
>>> not sure if this is one of the surprises that the author(s) had in
>>> mind! Could someone tell me whether this is expected, please?
>>
>> You'll be much less surprised if you do:
>>
>> Foo<- structure(list(new.env()), name="Foo")
>>
>> Attributes on reference objects are also passed by reference, and
>> surprises will result.
>
> Ah, it's good to know the core reason for the "surprises"! Sounds like
> the best thing is to refactor things as you suggest.
>
> Many thanks for all the responses.
>
> Regards,
> Jon
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



[Rd] Creating an environment with attributes in a package
John Chambers