reducing if statements and error handling

Alex Martelli aleax at aleax.it
Tue Aug 21 18:16:44 CEST 2001


"Jeff" <jhardcastle at solarc.com> wrote in message
news:e33814e8.0108210508.7644eeb5 at posting.google.com...
> Another easy newbie question here...  Suppose I have a method that
> accepts a string (called 'value') as an argument.  I want the method
> to check to see if the contents of the string is all numbers.  Here's

That's what string-method isdigit is for, indeed:-).

> def checkvalue(value):
>    if value.isdigit():
>         print 'success: ' + value + ' is a valid entry'
>         return 1
>    else:
>         print 'error: ' + value + ' is NOT a valid entry'
>         return -1
>
> Questions:
> 1) can I reduce this "if" logic down to one statement, perhaps using
> lambdas?

No, there is no way you can both print and return in "one statement"
(except a compound statement, like the if/else you're using here).

With some *HORRIDLY* convoluted obfuscations you might be able to
substitute the print statements with sys.stdout.write(...) calls,
and squeeze the whole body of function checkvalue into a single
return statement which emits messages as a "side effect"...
but why ever would you want to compose such a monstruosity...?
E.g., something like:
    return (sys.stdout.write(([
        'error: %s is NOT a valid entry'
        'success: %s is a valid entry',][value.isdigit()])%value)
        and 0) or [-1,1][value.isdigit()]
...but why would anybody obfuscate in such fashion...?

Besides, that wouldn't work if you wanted to raise in certain
cases only, anyway -- raise is also a statement.  And (see
below) it's better to raise on invalid value here...

> 2) is there a recommended approach for throwing errors?  In this case,
> I'd want to throw an error if the text is not a number and stop
> processing.  Can I define a custom exception to do that?  Should I

Of course!  E.g.:

class NoNumber(TypeError):
    pass

> catch the error in the logic that called the method and throw the
> exception there if the method returns a "-1", or should I throw the
> exception here?

Far better to raise here: this way, you can design upper layers
to let the exception propagate up to whatever level can best
handle it -- if you use return, you rely on the specific level
that's calling this function to check for the error-return value.
Not a good idea if you can avoid it, and raise lets you avoid it.


Alex






More information about the Python-list mailing list