<div class="gmail_quote">On 23 August 2012 10:05, Mark Carter <span dir="ltr"><<a href="mailto:alt.mcarter@gmail.com" target="_blank">alt.mcarter@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
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:<br>
<br>
def safe(x):<br>
# WHAT WOULD DEFINE HERE?<br>
<br>
print safe(666) # prints 666<br>
print safe(1/0) # prints 42<br>
<br>
I don't see how such a function could be defined. Is it possible?<br></blockquote><div><br></div><div>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:</div>
<div><br></div><div><div>>>> from contextlib import contextmanager</div><div>>>> @contextmanager</div><div>... def safe(default):</div><div>... try:</div><div>... yield default</div><div>... except:</div>
<div>... pass</div><div>... </div><div>>>> with safe(42) as x:</div><div>... x = 1/0</div><div>... </div><div>>>> x</div><div>42</div></div><div><div>>>> with safe(42) as x:</div><div>
... x = 'qwe'</div><div>... </div><div>>>> x</div><div>'qwe'</div></div><div><br></div><div>Oscar</div></div>