How to name Exceptions that aren't Errors

F. Petitjean littlejohn.75 at news.free.fr
Thu Apr 7 15:57:40 EDT 2005


Le 7 Apr 2005 19:23:21 GMT, Leo Breebaart a écrit :
> I've recently become rather fond of using Exceptions in Python to
> signal special conditions that aren't errors, but which I feel
> are better communicated up the call stack via the exception
> mechanism than via e.g. return values.
> 
> For instance, I'm thinking of methods such as:
> 
> 
>     def run(self):
>     """ Feed the input file to the simulator. """
> 
>         for linenr, line in enumerate(self.infile):
>             try:
>                 current_values = self.parse_line(linenr, line)
>==>         except CommentLineException:
>                 continue
>             results = self.do_one_simulation_step(current_values)
>             self.process_simulation_results(results)
> 
> 
> which I use in order to discard comments from a file I'm parsing
> line-by-line.
> 
[snip]
> 'Exception' prefix seems a bit redundant and pointless too. I
> suppose I could just call the exception "CommentLine" and leave
> it at that, but I don't know, maybe there's something better I'm
> overlooking.
You are overlooking the fact the flow of information is pretty much
linear. The comments lines can be safely ignored (filtered out) on the
fly.
                  enumerate             filter-out
infile(producer) --------> linenr, line -----------> linenr, line --->
> 
> Any suggestions?
 From your parse_line() method extract the logic to detect a comment line
put this code in a predicate function and use itertools.ifilter(pred,
iterable). Much more explicit. parse_line() is simplified. The client
code run() does not have to deal with bogus inputs anymore if you feed
it with the filtered out stream.
> 



More information about the Python-list mailing list