Error checking in Python

DavidW Blaschke dwblas at
Mon Jun 9 22:25:48 CEST 2003

With all due respect to the others who have posted a
reply,  a very small slowdown is better than having a
program abort.  You then have to track down the
reason, and if this is on a program written some time
ago, it may take a while to figure out that someone
was passing a string when the function expected an
int.  Also, it is proper programming etiqiette for a
function to ensure that is has the proper type, and
when necessary, to do bounds checking as well.  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.

BTW type checking can be done with:
     if type(1) == type( var ) :
        type("A") == 
although, it is easier to simply use:
     new_ var = int(var)
              = float(var)
              = str(var)
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
If you are concerned about slowdowns caused by a loop,
then simply code the function with a default that
tells it whether it should check. as in:

def my_funct( var, check=1 ):
    if check :
        ## type and bounds checking on var

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.


> --- In python-list at, BGM
> <no.spam at c...> 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.
> > 
> > -- 
> >

Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo.

More information about the Python-list mailing list