Why not just show the out-of-range index?

Roberto Bonvallet Roberto.Bonvallet at cern.ch
Fri Dec 8 06:20:25 EST 2006


"OKB (not okblacke)" wrote:
>> Can you give a real example from your code where the location of
>> such a human error (you cause a variable to bound to a value of
>> inappropriate type) would be difficult to find, plus an estimate of
>> how often you would make such an error?
> 
>        Here is an example:
> 
> self.outFile.write(str(len(self.hits)) + ' in ' + searchInfo.recordName 
> + '\t' + ']['.join((a. group() for a in self.hits)) + '\n')
> 
>        This is from a text-searching tool I have written to search 
> linguistic corpora.  This statement writes a summary line to the output 
> file indicating how many hits were found in that file.
[...]
>        The problem in this line was that I'd forgotten to put str() around 
> the len(). [...]

For printing formatted string, the best way to avoid such errors is using
the sprintf-like Python string formatting:

    self.outFile.write("%d in %s\t%s\n" % (
        len(self.hits),
        searchInfo.recordName,
        ']['.join(a.group() for a in self.hits)))

-- 
Roberto Bonvallet



More information about the Python-list mailing list