Guarding arithmetic

MRAB python at mrabarnett.plus.com
Thu Aug 23 07:21:25 EDT 2012


On 23/08/2012 12:01, Laszlo Nagy wrote:
>
>>>>> def safe(deferred, default=42, exception=Exception):
>> ...     try:
>> ...             return deferred()
>> ...     except exception:
>> ...             return default
>
> What a beautiful solution! I was wondering if the following would be
> possible:
>
>
> def test(thing, default, *exc_classes):
>       try:
>           thing()
>       except *exc_classes:
>           return default
>
>
> But it is syntactically invalid.
>
> Here is a workaround that is not so beautiful:
>
>
> def test(thing, default, *exc_classes):
>       try:
>           thing()
>       except Exception, e:
>           for cls in exc_classes:
>               if isinstance(e,cls):
>                   return default
>           raise
>
> print test( (lambda: 1/0), -1, ValueError, ZeroDivisionError) # prints -1
>
The 'except' clause accepts a tuple of exception classes, so this works:

def test(thing, default, *exc_classes):
     try:
         thing()
     except exc_classes:
         return default




More information about the Python-list mailing list