On 23 August 2012 10:05, Mark Carter <alt.mcar...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to