Pythonic API design: detailed errors when you usually don't care

Sybren Stuvel sybrenUSE at YOURthirdtower.com.imagination
Mon Oct 2 12:58:03 EDT 2006


Simon  Willison enlightened us with:
> try:
>   do_something()
> except HttpError:
>   # An HTTP error occurred
> except ApplicationError:
>   # An application error occurred
> else:
>   # It worked!
>
> This does the job fine, but has a couple of problems.

> I anticipate that most people using my function won't care about the
> reason; they'll just want a True or False answer.

Then they can use an except clause that catches the superclass of all
the possible exceptions your function raises.

> Their ideal API would look like this:
>
> if do_something():
>   # It succeeded
> else:
>   # It failed

This is the C way of doing things. The problem with relying on a
return value, is that failure could go unnoticed if the value isn't
checked. This might introduce nasty bugs.

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/



More information about the Python-list mailing list