Error checking in Python

DavidW Blaschke dwblas at yahoo.com
Tue Jun 10 16:06:53 EDT 2003


Assuming that you want more info than assert failed at
such and such a line number, check out try/except.

a ="abc"
try :
    assert int == type(a)
    print "Still in try:"
except :
    print a, "is not an integer -- program aborted"
    ## or invoke some error handler

You can also use a variable to turn the messages on or
off:

verbose = 1
if verbose :
    ##print out variable values and what's happening

You might use this if you are writing a new program
that called existing functions, and you want the
existing fuctions to tell you what data they receive
and how they react to it, without the additional
overhead under normal use.

Finally, changing a variable's type should only be
done if you have some sort of check afterwards.  A
simple example is a function that expects to receive
the month as an int.  It's o.k. to change the type to
int because you are going to be checking the bounds
anyway - 
assert 0 < month < 13.  I don't think anyone keeps
stats on this, but it has to be a fairly rare
occurance.  Sorry I brought it up in the first place
as it just led to confusion.

HTH
D.W

--- In python-list at yahoogroups.com, BGM <no.spam at c...>
wrote:
> 
> 
> Thanks a lot to all those who took the time to reply
to my question! 
Your
> replies have helped clarify things a little and
given me some food 
for
> thought. Coming from C, my instinct was to return
error codes. On 
some
> reflection, though, I think this is not necessarily
the best idea 
since if
> someone misunderstands your function enough to pass
the "wrong" arg, 
then
> they are likely not checking for any error codes
either, in which 
case
> after the return of the function, the program my
continue merrily 
along,
> or an exception will eventually be raised by python
anyway. In the 
former
> case, the user of the function might have an
extraordinarily tough 
time
> figuring out what is wrong.
> 
> A certain aspect of the replies interests me
greatly: That if one 
does no
> type-checking, the function lends itself to
previously unforseen
> generalization.... E.g. if the function were meant
to multiply some
> number by 2: x = x * 2 in which case that is also
valid even if x is 
a
> string! I wonder whether this phenomena is found to
be useful in 
practice?
> Does anyone know?
> 
> 
> 
> -------------------
> Regards,
> Gitonga Marete a.k.a BGM
>



__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com





More information about the Python-list mailing list