Python: decorator/wrapper for try/except statement
<p>I have some blocks of code which need to be wrapped by function.</p>

<pre><code>try:
    if config.DEVELOPMENT == True:
        # do_some_stuff
except:
    logger.info("Config is not set for development")
</code></pre>

<p>Then I'll do again:</p>

<pre><code>try:
    if config.DEVELOPMENT == True:
        # do_some_another_stuff
except:
    logger.info("Config is not set for development")
</code></pre>

<p>So, how can I wrap this "do_some_stuff" and "do_some_another_stuff"?</p>

<p>I'm trying to write function with contextmanager:</p>

<pre><code>@contextmanager
def try_dev_config(name):
    try:
        if name is not None:
            yield
    except Exception as e:
        print "not dev config"

with try_dev_config("config.DEVELOPMENT"):
    # do_some_stuff
</code></pre>

<p>And I got an error:</p>

<blockquote>
  <p>RuntimeError: generator didn't yield</p>
</blockquote>

<p>You could pass in a function.</p>

<pre><code>boolean = True

def pass_this_in():
    print("I just did some stuff")

def the_try_except_bit(function):
    try:
        if boolean:
            function()
    except:
        print("Excepted")


# Calling the above code
the_try_except_bit(pass_this_in)
</code></pre>

<p>If you want to reduce the "pass_this_in" definition bit, then you can use <a href="http://www.secnetix.de/olli/Python/lambda_functions.hawk" rel="nofollow">lambda function definitions</a>:</p>

<pre><code>pass_this_in = lambda : print("I just did some stuff")
</code></pre>

python try-catch wrapper decorator