Useful module to be written by a newbie

Peter Otten __peter__ at
Wed Apr 29 21:03:26 CEST 2015

Cecil Westerhof wrote:

> Op Wednesday 29 Apr 2015 18:27 CEST schreef Peter Otten:
>> Cecil Westerhof wrote:
>>> I have experience with Python, but it has been some time ago. The
>>> best way to relearn a language (for me) is just make a lot of code
>>> with it. But it would be nice if it was useful at the same time. I
>>> started a Python library on GitHub:
>>> Anyone an idea about functions and classes that would be useful for
>>> the Python community and could be written by me?
>> Realistically a Python coder with a little experience will have a
>> glance at your code and run away.
> Oops, that is not nice to hear. :'-( 

Sorry, I did not mean to discourage you or insult you, I just wanted to make 
it clear that your code is not there yet.

> But can you enlighten me? Then I can learn from it.

I was judging from the look of your MovingAverage.

I don't like the interface, it really should take an iterable so that you 
can write

>>> list(moving_average([1,2,3], 2))
[1.5, 2.5]

I don't see how you cope with error accumulation.

Given how generic your code is I don't see why you limit it to just int and 
float, and I don't expect that limitation to find errors caused by my code 
using your moving average. 

And then there's the testing...

Compare that to the beast I found in a web search for moving average python:


I'm no numerics expert and it would take me some time to verify that it is a 
good implementation without bugs or corner cases that affect my use case, 
but I can pick any three lines from the code and they just look right. If 
right now I needed an implementation of moving average that is more advanced 
than the naive one I can churn out

>>> def moving_average(values, n):
...     values = iter(values)
...     d = []
...     for i in range(n-1):
...         d.append(next(values))
...     for v in values:
...         d.append(v)
...         yield sum(d) / n
...         del d[0]
>>> list(moving_average([1,2,3], 2))
[1.5, 2.5]

and there is no implementation from a reputable project like numpy I'd 
certainly use that one rather than yours.

To put it into perspective: There are of course many areas where there is 
not much competition and if someone makes some exotic hardware accessible 
via Python then I am grateful and will accept that that person writes Python 
as if it were C and has not yet grokked the exact meaning of the global 
statement. In other words: useful wins over easy-to-use wins over idiomatic.

More information about the Python-list mailing list