python *args and **kwargs
<p>I have seen the previous stack overflow posts on this topic, but I am still unable to create use these two commands when I try to run my function. I have coded a demo example of a simple moving average that I would like to run through the args,kwargs command.</p>

<pre><code>import numpy as np
def moving_average(data,lookback=7,SMA=True): #MA function
    if SMA==True:
        weights=np.repeat(1.0,lookback)/lookback
        smas=np.convolve(data,weights,'valid')
        return smas
</code></pre>

<p>Just running this function works as expected.</p>

<pre><code>data=np.random.randn(100) #randomly 
moving_average(data,lookback=7,SMA=True) #this outputs the correct set of numbers
</code></pre>

<p>However the second I try to add args and kwargs it breaks down.</p>

<pre><code>def test1(*args,**kwargs):
    return moving_average(data,lookback,SMA)
test1(data,lookback=7,SMA=True) #this returns an error, saying my global lookback is not defined
</code></pre>

<p>What exactly in the *args **kwargs logic am I getting wrong? Ive tried inputting both a tuple and a dictionary but neither of those seem to work.</p>

<pre><code>def test1(*args,**kwargs):
</code></pre>

<p>Your function now has two local variables, <code>args</code> and <code>kwargs</code>. One holds the positional arguments that were passed in (as a tuple), the other the keyword arguments (as a dictionary).</p>

<pre><code>return moving_average(data,lookback,SMA)
</code></pre>

<p>Here you use three variable names (data, lookback and SMA) that don't exist in your function, so you get an error.</p>

<p>You could have done</p>

<pre><code>return moving_average(args[0], kwargs['lookback'], kwargs['SMA'])
</code></pre>

<p>But then your test1 function will only work with an exact call like <code>test1(data,lookback=7,SMA=True)</code>. A call like <code>test1(data, 7, True)</code> won't work, as then the parameters are all in <code>args</code>, none in <code>kwargs</code>).</p>

<p>Your function could also pass on the parameters exactly as it received them:</p>

<pre><code>return moving_average(*args, **kwargs)
</code></pre>

<p>That works, but there's no benefit to the <code>test1</code> function, it just calls <code>moving_average</code> and returns its results, why not call <code>moving_average</code> directly.</p>

python args kwargs