Guarding arithmetic
Peter Otten
__peter__ at web.de
Thu Aug 23 07:28:07 EDT 2012
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.
The except clause allows a tuple of exceptions:
>>> def safe(deferred, default, *exceptions):
... try:
... return deferred()
... except exceptions:
... return default
...
>>> safe(lambda: 1/0, -1, ValueError, ZeroDivisionError)
-1
More information about the Python-list
mailing list