Guarding arithmetic

Oscar Benjamin oscar.benjamin at bristol.ac.uk
Thu Aug 23 08:12:18 EDT 2012


On 23 August 2012 10:05, Mark Carter <alt.mcarter at gmail.com> 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?
>

It isn't possible to define a function that will do this as the function
will never be called if an exception is raised while evaluating its
arguments. Depending on your real problem is a context-manager might do
what you want:

>>> from contextlib import contextmanager
>>> @contextmanager
... def safe(default):
...     try:
...         yield default
...     except:
...         pass
...
>>> with safe(42) as x:
...     x = 1/0
...
>>> x
42
>>> with safe(42) as x:
...     x = 'qwe'
...
>>> x
'qwe'

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120823/96508a9f/attachment.html>


More information about the Python-list mailing list