new.instancemethod __iter__

Martin Drautzburg Martin.Drautzburg at
Sun Feb 7 11:13:41 CET 2010

Steven D'Aprano wrote:

> If you want iterator operations "similar to itertools", why does this
> mean you need to replace anything? Just create your own iterators.
> Or use pre-processing and post-processing to get what you want.
> Can you show an example of what you would like to happen?


my classes repesent musical objects. The fundamental paradigm I want to
apply is that of a Sequence, i.e. the most abstract aspect of music is
that "things" occur in a certain order.

Then I have a TimedSequence class, which is a Sequences whose elements
have a "time" attribute. I now want to be able to append such Sequences
by writing

s1 = TimedSequence (time=1,'a') # one-element Sequence
s2 = TimedSequence (time=2,'b')

y = s1*2 + s2

Naively appending those sequences would give me

but this is not what I want. Time needs to progress if I append a
sequence to another. So what I really want is something like


This implies that time is shifted to the next integer, but this is not
always the case. I need to know about some kind of "alignment". In
music this translates to "let a sequence start at the beginning of a
bar", or half bar or quarter note or whatever.

So I want to write

y = s1*2 + s2(align=10)

which should iterate as


I have no difficulty passing "align" to the object (using __call__) and
use it while I furnish my own __iter__() method. However I don't quite
see how I can do this with bare itertools, though I may be wrong here.

Bare in mind that it is not only about somehow getting the job done. The
beauty of the resulting syntax is also important.

More information about the Python-list mailing list