Bobe Kryant Bobe Kryant - 3 months ago 24
Python Question

python *args and **kwargs

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.

import numpy as np
def moving_average(data,lookback=7,SMA=True): #MA function
if SMA==True:
return smas

Just running this function works as expected.

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

However the second I try to add args and kwargs it breaks down.

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

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.


Pass the *args and **kwargs to your function not the argument(s) and named argument(s):

def test1(*args,**kwargs):
    return moving_average(*args, **kwargs)