Confused compare function :)
python.ml.bruno.dupuis at lisael.org
Thu Dec 6 09:49:26 CET 2012
On Thu, Dec 06, 2012 at 04:32:34AM +0000, Steven D'Aprano wrote:
> On Thu, 06 Dec 2012 03:22:53 +0000, Rotwang wrote:
> > On 06/12/2012 00:19, Bruno Dupuis wrote:
> >> [...]
> >> Another advice: never ever
> >> except XXXError:
> >> pass
> >> at least log, or count, or warn, or anything, but don't pass.
> > Really? I've used that kind of thing several times in my code. For
> > example, there's a point where I have a list of strings and I want to
> > create a list of those ints that are represented in string form in my
> > list, so I do this:
> > listofints = 
> > for k in listofstrings:
> > try:
> > listofints.append(int(k))
> > except ValueError:
> > pass
> > Another example: I have a dialog box with an entry field where the user
> > can specify a colour by entering a string, and a preview box showing the
> > colour. I want the preview to automatically update when the user has
> > finished entering a valid colour string, so whenever the entry field is
> > modified I call this:
> > def preview(*args):
> > try:
> > previewbox.config(bg = str(entryfield.get()))
> > except tk.TclError:
> > pass
> > Is there a problem with either of the above? If so, what should I do
> > instead?
> They're fine.
> Never, ever say that people should never, ever do something.
Well, dependening on the context (who provides listofstrings?) I would
log or count errors on the first one... or not.
On the second one, I would split the expression, because (not sure of
that point, i didn't import tk for years) previewbox.config and
entryfield.get may raise a tk.TclError for different reasons.
The point is Exceptions are made for error handling, not for normal
workflow. I hate when i read that for example:
(loads of them in many libraries and frameworks)
if k in mydict:
Note that the performances are better with the latter.
There are some exceptions to this, though, like StopIteration
For me, it's a rule of thumb, except: pass is possible in situations
where I control every input data, and I deeply, exactly know all code
interractions. If figuring all this out is longer (it's almost always
the case) than typing:
log.warning('oops:\n %s' % traceback.format_exc())
It depends also on the context, I'd be more 'permissive' a short
script than into a large program, framework, or lib, for the
very reason it's easy to know all code interactions.
In my coder life, i spent more time debugging silently swallowed exceptions
than logging abnormal behaviours.
More information about the Python-list