Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Message generation in mathematica

In a module I'm writing I have (for the development and testing phases) lots of Print["Messages"]. I have two questions:

  1. What is the best practice to print such "debugging" messages?
  2. Is there a way to call the module such that the messages will NOT be printed? For example, when calling the module from another module, I would like not to see all the output of the first one.
like image 627
Dror Avatar asked Jan 02 '12 08:01

Dror


1 Answers

I like to always keep global variables prefixed with the $, and functions without the prefix, so I'd write:

debugPrint[args___] := $debugPrintFunction[args]

$debugPrintFunction = Print[##] &

Then you can just use debugPrint exactly like you'd use Print now. When you want to get rid of the debugging messages, you just unset the variable:

$debugPrintFunction = .

There are some advantages to doing it this way. One is that you can use Block to switch the debugging on and off locally:

In[1]:= foo[x_] := (debugPrint[x]; x+1)

In[2]:= foo[3]
3
Out[2]= 4

In[3]:= Block[{$debugPrintFunction}, foo[3]
Out[3]= 4

You can even locally make $debugPrintFunction do something else, like Sow values for a Reap to pick up, or direct the debugging messages somewhere else, like

strm = OpenWrite["your/log/path/here", InputForm];
Block[{$debugPrintFunction = Write[strm, ##]},
  foo[3]];
Close[strm];

Used judiciously, the dynamic scoping provided by Block allows the use of global variables in a relatively safe and controlled way.

like image 188
Pillsy Avatar answered Dec 09 '22 04:12

Pillsy