Re: [Rd] The default behaviour of a missing entry in an environment

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Fri, 13 Nov 2009 14:27:57 -0500

On 11/13/2009 2:03 PM, Trishank Karthik Kuppusamy wrote:
> Greetings everyone,
>
> I have a question about the default behaviour of a missing entry in an environment.
> Let us look at the following sequence of R statements:
>

>> e <- new.env()
>> e$a <- 1
>> e$a

> [1] 1
>> e$b

> NULL
>> 

>
> I think I understand the logic for returning NULL to a missing entry in an environment,
> but I do not think that it is fully justified.
> I am sure that the R developers must have seen this argument before,
> but I wish to call for attention to this problem again,
> because I think that it is important to the default safety of the R programming language.

You get the same behaviour when asking for a nonexistent element of a list, or a nonexistent attribute. If you want stricter checking, don't use $, use get():

 > get("b", e)
Error in get("b", e) : object 'b' not found

or check first with exists():

 > exists("b", e)
[1] FALSE
> I suppose that one could argue that a good R programmer must be careful
> not to use NULL in any of his environment entries,
> but I think it is better to remove altogether this burden from the programmer
> and simply raise a good, old-fashioned exception when the "$" operator
> encounters a missing entry in an environment.

But then it would be inconsistent with what it does in other situations.

Duncan Murdoch

> The biggest advantage is that it will easily eliminate a whole class of programming error.
> The biggest disadvantage is that it is not backwards-compatible with old R programs.
>
> I suppose a personal solution would be to simply redefine the "$" operator in my programs.
> However, I really do think that the default safety of an R environment matters very much.
> At the very least, it would be nice to be able to configure the safety of a new environment,
> perhaps through a parameter.
>
> -Trishank
> ______________________________________________
> R-devel_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Fri 13 Nov 2009 - 19:30:29 GMT

This archive was generated by hypermail 2.2.0 : Sat 14 Nov 2009 - 00:30:24 GMT