Other sites

Oh (de)bugger! Part II

It’s Friday night, and I recently discovered that adding a dash of Cointreau somewhat enhances a gin and tonic. Consequently, I’m drunk-blogging. Will try not to make too many tpyos.

In the first part of this series, I discussed some standard debugging techniques, like the use of the browser function. One of the limitations of browser is that it isn’t much help if the problem is somewhere higher up the call-stack. That is, the case when you passed a dodgy argument to another function, which maybe passed it on to something else before your code fell over.

If you have an error, but you don’t know where it is, then a helpful thing to see is your call stack, and the variables that you’ve put in it. The function I’m going to show you uses sys.calls to retrieve the call stack, and sys.frames to retrieve the environment for each function you called. Next it calls ls.str in each of those environments to tell you what variables you’ve created. Finally, there are some methods to print your output more clearly. After all, the whole point of this function is to give you quick insight into what you’ve just done.

When I was trying to think of a suitable name for this function, I toyed with variations on the word “stack”. Eventually, I figured that it should be named for the word most commonly used when things go wrong. And so, I present to you, the bugger function.

The call to make.names is there to ensure that each items in call_stack and ls_stack have a unique name, and thus can be referenced more easily. To finish, these two components get S3-style overloads of the print function.

One thing to note is that ls.str doesn’t pick up the ... arguments. It is possible to retrieve the call to those dots from each environment, but it isn’t always possible to evaluate them. Playing with R’s evaluation model in this way is deep magic, so accessing them involves excessive use of substitute and eval. I’m going to postpone talking about them for an occasion that didn’t involve gin and cointreau.