Guarding arithmetic

Laszlo Nagy gandalf at shopzeus.com
Thu Aug 23 07:01:47 EDT 2012


>>>> 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





More information about the Python-list mailing list