function decorators to specify the first two lines of the def?
<p>I'm on python 3.5:</p>

<p>I have a repeating pattern in some of my python functions. For a large collection of classes the first two lines are:</p>

<pre><code>obj_a = &lt;..... obtain something I need.....&gt;
obj_b = &lt;..... obtain another thing I need....&gt;
</code></pre>

<p>I'm simplifying it here, but the process of obtaining <code>obj_a</code> and <code>obj_b</code> isn't a one liner... I would like to avoid repeating this code anywhere in a more elegant way than a util function to obtain <code>obj_a</code> and <code>obj_b</code> (e.g. <code>obj_a = getObjectA()</code>...) </p>

<p>Is there any way to take those lines and put them as part of a decorator of a function where I have something like:</p>

<pre><code>@function_where_I_need_my_objects
def foo:
  &lt;....do something with obj_a and obj_b already initialized....&gt;
</code></pre>

<p>You could do something like the following which creates variables that will effectively become local to the function when it's called. This uses <code>eval()</code> which can be unsafe if used on untrusted input, but that is not the case here where it's being used to execute the compiled byte-code of a decorated function (but <em>caveat emptor</em>).</p>

<pre><code>def local_vars(**kwargs):
    """ Create decorator which will inject specified local variable(s) into
        function before executing it.
    """
    def decorator(fn):
        def decorated():
            return eval(fn.__code__,
                        {k: v() for k, v in kwargs.items()}) # call funcs
        return decorated
    return decorator

def get_object_a(): return 13
def get_object_b(): return 42

# create abbreviation for the long decorator
obj_decorator = local_vars(obj_a=get_object_a, obj_b=get_object_b)

@obj_decorator  # apply decorator
def test():
    print(obj_a)
    print(obj_b)

test()
</code></pre>

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>13
42
</code></pre>

python python-3.x