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

Carl Banks pavlovevidence at
Mon Oct 2 19:30:44 CEST 2006

Simon  Willison wrote:
> I have an API design question. I'm writing a function that can either
> succeed or fail. Most of the time the code calling the function won't
> care about the reason for the failure, but very occasionally it will.
> I can see a number of ways of doing this, but none of them feel
> aesthetically pleasing:

Whether it's aesthetically pleasing or not, raising an exception is the
way to do it.

You seem to care about your users.  Keep this in mind: if your function
returns an error code, then it puts an burden on users to A. always
check for errors, and B. always check for errors right at the point
where the function is called.

Python has exceptions so that programmers can write code without
checking for an error in every other line like they would have to in C.
 With exceptions, users are free to not bother checking for errors, if
program termination is acceptable, or to handle the exception somewhere
else.  Please don't circumvent this on the misguided pretense of
"helping" the user.

If you really think most users would prefer to check the return value
for an error, then I'd recommend two versions of the function: the
regular, Pythonic version that raises exceptions, and the convenience
version that swallows the exception and returns a code.  (Compare a[1]
vs. a.get(1).)

> This is nice and simple but suffers from cognitive dissonance in that
> the function returns True (or an object evaluating to True) for
> failure.

BTW, this is true in a lot of places.  Back in the days of DOS, zero
meant success, non-zero was an error code.  Zero also signals success
for process exit codes on Unix.  Also on Unix, negative values are
often considered errors, non-negative success.  The idea that error ==
0 is not self-evident, and often not true.

If it helps, consider using string error codes, or defining some
constants to check against ("if error == NO_ERROR").

Carl Banks

More information about the Python-list mailing list