Error checking in Python

Andrew Wilkinson ajw126 at NOSPAMyork.ac.uk
Mon Jun 9 10:24:55 EDT 2003


BGM wrote:

> 
> Hello all:
> 
> I am new to python, coming from a modest C background. Recently, I was
> writing some custom module in Python and I was wondering about one thing:
> Since the user of the module can pass any argument they wish, then it
> seemed like a good idea to check ,say, for type errors within the
> functions in the module. However, it occurred to me that if some of these
> functions are used in in the inner loops of some program, there could be a
> significant slow-down. When writing their own modules, what do the users
> of the list usually do? Do you leave the responsibility for type checking
> to the user of the functions, or do you implement this in the modules, or
> some combination of these two approaches?
> 
> I apologize if there is a simple mechanism that Python provides that I
> have perhaps not learned about. (Other than throwing an exception during
> runtime)
> 
> -------------------
> BGM.

The simplest answer to this is to look at the standard library, there you
have loads of well tested, well used modules - most of which are coded in
Python.

It's almost always a bad idea to explicitly test for types in Python code,
because what happens if the user passes an object that acts like the type
you were expecting, but actually isn't. A good example of this is the
StringIO (http://www.python.org/doc/current/lib/module-StringIO.html)
class. It appears to be a file, but in actual fact is a string - because
methods in Python aren't looked up until they are called it can be used
whereever a file is required. The same goes for a class overriding
__getitem__ and __setitem__ and appearing to be a list.

If you want to add some form of error checking to your functions then the
assert statement (http://www.python.org/doc/current/ref/assert.html) is a
good thing to use as it gets compiled out when the -O flag is used.

e.g.
assert type(number) == int # this is Python 2.2 or above only (I think)

Hope this helps,
Andrew Wilkinson




More information about the Python-list mailing list