If/then style question

Joel Koltner zapwireDASHgroups at yahoo.com
Thu Dec 16 20:39:30 EST 2010


"Steven D'Aprano" <steve+comp.lang.python at pearwood.info> wrote in message 
news:4d0aa5e7$0$29997$c3e8da3$5496439d at news.astraweb.com...
> It doesn't look like you were learning Python. It looks like you were
> learning C with Python syntax :(

True, although in many cases one has to interface to legacy C code where it'd 
be rather more code to start throwing exceptions left or right... since sooner 
or later those exceptions would still have to be turned into a single status 
(error) code!

> which all too often becomes:
>
> result = obj.myMethod(arg1, arg2)
> if result == good1:
>    do_something_good()
> else:  # assume result is bad1
>    handle_error1()

This really isn't a bad way to go *if you weren't planning on spending the 
time to really, fully flesh out the individual error cases anyway.*  I see 
this pretty often: Peple put in sophisticated exception handling 
infrastructure, but when an error actually occurs, all six dozen cases handled 
individually end up just printing some generic message and exiting the program 
anyway.

In an ideal world all the error cases would do something "smart," but 
pragmatically one has to balance how likely an error is to occur and how much 
damage it does with how much time you want to spend making a really smart 
error handler.

> or even:
>
> who_cares = obj.myMethod(arg1, arg2)
> do_something_good()

Even this can be OK if do_something_good() behaves in a relatively benign 
fashion when feed gibberish.  I mean, how many people actually check to see 
whether or not printf() succeeded, you know?

But I would agree that often you see...

who_care = obj.myMethod(arg1, arg2)
do_something_really_dangerous_that_depends_on_the_success_of_myMethod()

:-)

> Well, that's better, but still more like C rather than Python. Avoid the
> anti-pattern of returning in-band error codes.

The main sticky point here is that what's an "error" vs. a "warning" or "note" 
(but not "success") is often rather a grey area.  E.g., Pyhton's open() raises 
an IOError is the file can't be opened, but in my mind that's still a common 
enough/expected occurrence that elevating its behavior to an exception is more 
a judgement call than something everyone would agree on.  (On the other hand, 
trying to read or write to an un-opened file is now clearly in the realm of an 
error and deserves an exception.)

---Joel




More information about the Python-list mailing list