Possible Duplicate:
What is the Python equivalent of static variables inside a function?
I try to write a recursive function. It iterates over a vector and gives a value which depends upon current value and previous value. In Matlab I can declare a variable as persistent
inside the function and the value is stored in memory after the function is called, so next call of the function start from the previous values.
This is what i started for simple moving average:
def AvgFilter(x):
if not firstRun: # checks if runs for first time, i.e. firstRun is empty
k = 1 # setup initial variables if run for first time
prevAvg = 0 # prevAvg - the average calculated during last call
firstRun = 1 # only for initialisation
alpha = (k-1)/k
avg = alpha * prevAvg + (1 - alpha)*x
prevAvg = avg
k = k + 1
return avg
I need the variables k
prevAvg
firstRun
to be remembered between function calls. I read it can be done via decorator, I did try to implement it seting @counter
before function but not sure how I should implement it. Is decorator the only way (did not find anything else)? and how to write counter function to store my variables? I bit worry that later on with more complicated recursions I will be completely lost with the idea of decorator.