Debugging flags [was: Re: PEP 285: Adding a bool type]

Bengt Richter bokr at oz.net
Mon Apr 1 15:21:42 EST 2002


On Mon, 1 Apr 2002 08:05:24 -0500, "Steve Holden" <sholden at holdenweb.com> wrote:

>"phil hunt" <philh at comuno.freeserve.co.uk> wrote ...
>[...]
>> I've gone through some of my herbivore code, looking to see where
>> I've used 0 or 1 as a boolean. Example 1:
>>
>> debug = 0  # debugging this module?
>>
>> Frankly, if that is unclear to anyone, they are not cut out to be a
>> programmer. Bear in mind that most non-programmers are aware of the
>> 0/1 paradigm for boolean values: it appears on much electrical
>> equipment.
>>
>I find it much more helpful to use
>
>    debug = (1, 2, 7, 93) # debugging parsing, tree build, code generation
>and error messages
>
>with corresponding tests like
>
>    if 7 in debug:
>        ...
I wonder if that would be faster as
     if debug and 7 in debug

>
>Given that when I'm not debugging the list is empty, these tests are not
>unduly time-consuming. But then I've often gone over the top to allow
>selective testing in complex developments.
>
I haven't had occasion to do it in Python, but I think magic letters
are easier to remember than magic numbers ;-)

debug = raw_input('Enter a string of characters for tests to enable: ')
...
if debug and 'x' in debug:
   # do x-test
...
etc.

Hm, for full mnemonics, you could make debug a list of words:

debug = raw_input('Enter names of tests to enable (separated by spaces): ').split()
...
if debug and 'foo-test' in debug:
...
etc.

I've used letters to do it in C, a little differently.
It can be useful, especially to avoid recompiling. And you
can do it so you can recompile with all the tests excluded, by
changing just one line, and without using #if/#endif clutter.

(Untested reconstruction from memory, XXX for concise example ;-)

#define IF_DEBUG_ENABLED(x) if(debug & (1<<(ord(x)-ord('a')))
// to compile out debug code (make it dead code), use the next line instead
// #define IF_DEBUG_ENABLED(x) if(0)
long debug = 0;
for(char *p = argv[1]; *p; ++p){ // XXX assuming available on cmd line
   debug |= (1<<(ord(*p)-ord('a'))); // XXX no warning if unhandled chars
}
...
IF_DEBUG_ENABLED('x'){	// test x enabled?
...
}
etc.

Regards,
Bengt Richter



More information about the Python-list mailing list