Popular recipes tagged "guard"http://code.activestate.com/recipes/tags/guard/popular/2017-06-25T17:17:43-07:00ActiveState Code RecipesGuard against an exception in the wrong place (Python)
2017-06-25T17:17:43-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/580808-guard-against-an-exception-in-the-wrong-place/
<p style="color: grey">
Python
recipe 580808
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/context/">context</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/guard/">guard</a>, <a href="/recipes/tags/manager/">manager</a>).
Revision 2.
</p>
<p>Sometimes exception handling can obscure bugs unless you guard against a particular exception occurring in a certain place. One example is that <a href="https://www.python.org/dev/peps/pep-0479/">accidentally raising <code>StopIteration</code> inside a generator</a> will halt the generator instead of displaying a traceback. That was solved by PEP 479, which automatically has such <code>StopIteration</code> exceptions change to <code>RuntimeError</code>. See the discussion below for further examples.</p>
<p>Here is a class which can be used as either a decorator or context manager for guarding against the given exceptions. It takes an exception (or a tuple of exceptions) as argument, and if the wrapped code raises that exception, it is re-raised as another exception type (by default <code>RuntimeError</code>).</p>
<p>For example:</p>
<pre class="prettyprint"><code>try:
with exception_guard(ZeroDivisionError):
1/0 # raises ZeroDivisionError
except RuntimeError:
print ('ZeroDivisionError replaced by RuntimeError')
@exception_guard(KeyError)
def demo():
return {}['key'] # raises KeyError
try:
demo()
except RuntimeError:
print ('KeyError replaced by RuntimeError')
</code></pre>
Function guards for Python 3 (Python)
2016-05-01T13:11:05-07:00Dmitry Dvoinikovhttp://code.activestate.com/recipes/users/2475216/http://code.activestate.com/recipes/580658-function-guards-for-python-3/
<p style="color: grey">
Python
recipe 580658
by <a href="/recipes/users/2475216/">Dmitry Dvoinikov</a>
(<a href="/recipes/tags/call/">call</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/dispatch/">dispatch</a>, <a href="/recipes/tags/function/">function</a>, <a href="/recipes/tags/guard/">guard</a>).
</p>
<p>This module implements a function guard - facility to redirect the the call to one of several function implementations at run time based on the actual call arguments.</p>
<p>Wrap each of the identically named functions in a @guard decorator and provide a _when parameter with a default value set to guarding expression.</p>
<p>See samples at the top of the module.</p>