473,387 Members | 1,574 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

iterator idea

I wonder if Python would benefit from letting a generator jump to
another iterator, i.e. something like

yield return *seq

would be the equivalent of

for s in seq: yield s
return

except that it would work by transferring control directly to seq's
iterator (like a goto) instead of calling it like a subroutine. The
idea is to solve one of the perennial iterator annoyances, the
inability to push items back on an iterator. For example, the
annoyance means itertools.takewhile consumes an extra element with no
reasonable way to retrieve it. The new feature would let us write
something like (obviously untested):

def takewhile_exact (pred, seq):
"""return two iterators (head,tail). head is the same as
itertools.takewhile(pred,seq). tail is the rest of the
elements of seq, with none missing. You can't use tail
until you've iterated through head."""
buf = []
def head():
for s in seq:
if pred(s): yield s
# save non-matching item so that tail can find it
buf.append(s)

def tail():
if not buf:
raise IndexError, "not yet ready"
yield buf.pop()
yield return *seq # transfer control to seq

return head(), tail()

The reason tail() can't just iterate through seq is that you
might call takewhile_exact many times:

def is_even(n): return (n%2 == 0)
def is_odd(n): return (n%2 != 0)

# we want to do something with all the runs of even numbers
# in the sequence, and similarly with the odds. seq is an
# infinite sequence.
while True:
evens, seq = takewhile_exact(is_even, seq)
do_something_with (evens)
odds, seq = takewhile_exact(is_odd, seq)
do_something_else_with (odds)

Without the "goto"-like transfer, we'd get deeper and deeper in nested
iterators and eventually overflow the call stack.
Oct 26 '06 #1
2 1124
Paul Rubin <http://ph****@NOSPAM.invalidwrote:
....
For example, the annoyance means itertools.takewhile consumes an extra
element with no reasonable way to retrieve it.
....
>
def is_even(n): return (n%2 == 0)
def is_odd(n): return (n%2 != 0)

# we want to do something with all the runs of even numbers
# in the sequence, and similarly with the odds. seq is an
# infinite sequence.
while True:
evens, seq = takewhile_exact(is_even, seq)
do_something_with (evens)
odds, seq = takewhile_exact(is_odd, seq)
do_something_else_with (odds)

Without the "goto"-like transfer, we'd get deeper and deeper in nested
iterators and eventually overflow the call stack.
I wouldn't agree that there is no way reasonable way to get the terminating
value with takewhile, you just need another generator or two:
>>def repeatable(iterator):
it = iter(iterator)
for v in it:
while (yield v):
yield None

>>def takeparts(predicates, iterator):
iterator = repeatable(iterator)
while True:
for pred in predicates:
yield takewhile(pred, iterator)
iterator.send(True)

>>for seq in takeparts([is_even, is_odd], [2,2,4,5,6,6,7]):
print list(seq)
[2, 2, 4]
[5]
[6, 6]
[7]

Oct 26 '06 #2
Duncan Booth <du**********@invalid.invalidwrites:
I wouldn't agree that there is no way reasonable way to get the terminating
value with takewhile, you just need another generator or two:
Hmm, I hadn't thought about iterator.send. I'll have to look at that
more carefully and re-read the PEP.
Oct 26 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Rex_chaos | last post by:
Hi all, I am writing my own container and need an iterator. I am hesitating if I should my iterator should inherited from std::iterator or just write my own one. Please give me an idea. BTW,...
26
by: Michael Klatt | last post by:
I am trying to write an iterator for a std::set that allows the iterator target to be modified. Here is some relvant code: template <class Set> // Set is an instance of std::set<> class...
26
by: Michael Klatt | last post by:
I am trying to write an iterator for a std::set that allows the iterator target to be modified. Here is some relvant code: template <class Set> // Set is an instance of std::set<> class...
13
by: Adam Hartshorne | last post by:
Hi All, I was wondering if anybody can tell me what is wrong with the following code, in a .h file I have std::list<std::vector<Site> > positions ; std::list<std::vector<Site> >::iterator...
0
by: mailforpr | last post by:
Hi. Let me introduce an iterator to you, the so-called "Abstract Iterator" I developed the other day. I actually have no idea if there's another "Abstract Iterator" out there, as I have never...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.