Error checking in Python
no.spam at comcast.net
Tue Jun 10 08:19:26 CEST 2003
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?
Gitonga Marete a.k.a BGM
On 10 Jun 2003, John J. Lee wrote:
> DavidW Blaschke <dwblas at yahoo.com> writes:
> > With all due respect to the others who have posted a
> > reply, a very small slowdown is better than having a
> > program abort.
> Sigh. That's not the point.
> This has been discussed *so* many times before, with universal
> acceptance amongst people who have actually listened to the arguments
> and thought about it.
> > BTW type checking can be done with:
> > if type(1) == type( var ) :
> > type("A") ==
> > etc.
> When you *do* typecheck, use isinstance(a, b), not type(a) = b.
> > 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.
> Is this a troll? Have you heard of exceptions?
> > 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.
> Well... the question of whether / when to assert invariants rather
> than raise exceptions is an interesting one, and I certainly haven't
> made up my mind. The usual Python approach seems completely at odds
> with Meyer's way of doing things (as in Eiffel), so I've been
> surprised to see people doing that style of programming in Python.
More information about the Python-list