HowCanI: inlined exceptions

Shae Erisson shapr at uab.edu
Fri May 26 18:11:59 EDT 2000


Pete Shinners wrote:

> what i'd really,really like to do is define something
> that works like this
> 
> def catch(expression, errcode=None):
>     try:
>         return expression:
>     except:
>         return errcode
> 
> if __name__ == '__main__':
>     name = catch(fields[1], 'Anonymous')
>     age = catch(now-birth, 100)
>     pet = catch(findpet(name, age)) or 'No Pet'
> 
> i would really like to do this for myself, because i
> would use it extensively! i understand the problem
> here is that my "expression" is being evaluated
> before the function is getting called, so the
> exception is raised outside of my function.

If your functions return false* upon failure, you could do:

name = fields[1]
if not name:
    name = 'Anonymous'

which can then be simplified to the slightly less readable form of:

name = fields[1] or 'Anonymous'

*false in Python is zero, empty string, empty list, empty tuple, or
None, and anything else is true. (unless I'm missing something)

The only gotcha you might run across is that this does not deal with
handling errors at all, this is just a different way of approaching the
same idea.

It seems to me that many modules in python return None if they don't
find what they're looking for, but maybe that just means I've been using
the re module too much.

This may be an answer to a question you didn't ask, but I hope it's
helpful.
-- 
sHae mAtijs eRisson (sHae at wEbwitchEs.coM) gEnius fOr hIre
   bRing mE fIve sQuirrels aNd nO oNe wIll gEt hUrt
13:00pm up 1 season, 1 squirrel, load average: 1+1j 0.5+2j 0.2+0.5j



More information about the Python-list mailing list