Error checking in Python

Steven Taschuk staschuk at telusplanet.net
Mon Jun 9 18:23:06 EDT 2003


Quoth DavidW Blaschke:
> [...] Also, it is proper programming etiqiette for a
> function to ensure that is has the proper type, [...]

Like this?

    def double(n):
        if not isinstance(n, int):
            raise TypeError('%r is not an int!' % (n,))
        return 2*n

If the object can't be multiplied by an integer, the '2*n' will
throw an exception anyway, so what have you gained?  If it can,
but you didn't anticipate it in your type checking, you've lost
functionality; this function can't be used with floats, longs,
strings, lists, user-defined types representing vectors, matrices,
permutations, etc..

All the "type checking" is doing here is discarding the benefits
of signature-based polymorphism.

> [...] That
> way, you can pass a variable to a function without
> having to find the source every time, to check and see
> what kind of a variable it requires.

Read help(func).  Or just try it and see what happens.  Python's
interactivity is your friend.

  [...]
> Always check for "None" or an empty string first, and
> you have to return some sort of default error
> indicator if the variable is empty or can not be
> processed.

Ag.  Don't return error indicators; raise exceptions.  That's what
they're for.

  [...]
> In general, you should be able to call a function
> without worrying about any of the consequences.  It is
> the functions job to verify and alter when, and if
> possible.  An old, old saying is to write code that is
> iron-clad, meaning that it can handle almost anything
> that is thrown at it.  Sissy functions cost much more
> in the long run.  Good question though.  It shows that
> you want to develop good programming habits.

I'm pretty sure I disagree with this entire paragraph.  Certainly
it comprehensively contradicts the principles of agile
methodologies.

-- 
Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1





More information about the Python-list mailing list