[R] Lexical scoping is not what I expect
Terry Therneau
therneau at mayo.edu
Thu Jun 27 14:51:28 CEST 2013
Duncan,
"I disagree with Duncan" was not at all the intent of my note, but on rereading it does
have that flavor. Chastisement accepted. Due to the documentation angle I'd simply
change your original "maybe" to "sometimes maybe". A bit more caution but the same message.
Terry T.
On 06/27/2013 07:24 AM, Duncan Murdoch wrote:
> On 13-06-27 8:18 AM, Terry Therneau wrote:
>> I second Ellison sentiments of "almost never". One main reason is readability on later
>> viewing.
>> Yes, as Duncan says global variables can sometimes be handy and make functions quick to
>> write, but using a formal argument in the call is always clearer.
>
> I didn't say that. I said that in most cases global variables other than functions
> should not be used.
>
> I would generalize that a little: global constants are okay, changing globals is
> usually a bad idea.
>
> Duncan Murdoch
>
>
>>
>> Terry Therneau
>>
>> On 06/27/2013 05:00 AM, r-help-request at r-project.org wrote:
>>> On 13-06-26 6:57 AM, S Ellison wrote:
>>>>>
>>>>>
>>>>>>> -----Original Message-----
>>>>>>> It may be helpful not to worry about the technical details,
>>>>>>> just to look at the source code defining the function: if it
>>>>>>> is defined in a place where a variable can be seen, it can
>>>>>>> see that variable.
>>>>>
>>>>> I too find R's lexical scoping rules straightforward.
>>>>> However, I'd say that if your code relies on lexical scoping to find something,
>>>>> you should probably rewrite your code.
>>>>>
>>>>> The number of times I've seen new R users get unexpected results because they
>>>>> haven't noticed that their function is referencing a parent environment instead of a
>>>>> locally defined variable or argument is past counting.
>>>>>
>>>>> Of course there are times when it's useful and sensible to have globally defined
>>>>> variables that can be accessed within a function. But they are very rare; as a
>>>>> default, I'd recommend avoiding it if at all possible. If your function needs
>>>>> something from outside, pass it as an argument.
>>>>>
>>> I would say the meaning of "probably" in your 2nd sentence depends quite
>>> a bit on the user. For beginners, it's "almost certainly". For people
>>> who are comfortable with the concept, it's just "maybe".
>>>
>>> I would agree that in most cases the only global objects that functions
>>> should reference are other functions, but small nested functions are
>>> quite safe, and it's sometimes useful to create functions in a local
>>> environment so they have persistent memory.
>>>
>>> Duncan Murdoch
>>>
>
More information about the R-help
mailing list