Guarding arithmetic
Peter Otten
__peter__ at web.de
Thu Aug 23 06:11:21 EDT 2012
Mark Carter wrote:
> Suppose I want to define a function "safe", which returns the argument
> passed if there is no error, and 42 if there is one. So the setup is
> something like:
>
> def safe(x):
> # WHAT WOULD DEFINE HERE?
>
> print safe(666) # prints 666
> print safe(1/0) # prints 42
>
> I don't see how such a function could be defined. Is it possible?
1/0 is evaluated before safe() is called. Therefore safe() has no chance to
catch the exception. You have to move the evaluation into the safe()
function:
>>> def safe(deferred, default=42, exception=Exception):
... try:
... return deferred()
... except exception:
... return default
...
>>> print safe(lambda: 666)
666
>>> print safe(lambda: 1/0)
42
More information about the Python-list
mailing list