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><code>obj_a</code> and <code>obj_b</code> sound a lot like state.</p>

<pre><code>class Thing:
    def __init__(self):
        # These could also be class attributes instead
        # if they can be initialized when Thing is first
        # defined.
        self.obj_a = ...
        self.obj_b = ...

    def foo(self):
        # use self.obj_a and self.obj_b

t = Thing()
t.foo()
</code></pre>

<p>Defining a decorator that returns a closure around <code>obj_a</code> and <code>obj_b</code> is also possible.</p>

<pre><code>def decorator(f):
    obj_a = ...
    obj_b = ...
    def _():
       # use obj_a and obj_b
    return _

@decorator
def foo():
    ...
</code></pre>

<p>However, it is hardly any longer and much more flexible to simply write a function that <em>returns</em> the two objects, and lets the caller use whatever names they like:</p>

<pre><code>def _get_a_b():
    a = ...
    b = ...
    return a, b

def foo():
   obj_a, obj_b = _get_a_b()
   ...

def bar():
    a1, a2 = _get_a_b()
    ...
</code></pre>

python python-3.x