switch recipe?
Mark McEahern
marklists at mceahern.com
Sat Jul 13 02:07:27 EDT 2002
[Tim Peters]
> Then that's where we differ: I don't consider an empty sequence to be "an
> error" in any sense of the word. For the same reason, range(10,
> 10) doesn't complain in Python, or string[i:i], etc -- doing nothing
> gracefully is important because there's sometimes nothing that needs
> be done <wink>.
I think I'll continue to scratch my head and profit from that observation
for quite some time. Thank you.
Profit--or better yet, lose. My misconceptions, that is. <wink>
So where I've ended up is a place I'm sure there's some fancy name for--but
I don't know it.
I have two iterators, one is finite, the other is a repeating alternator. I
want to walk through both of them at the same time, which means I'll stop
when the finite one is done. (If I need to stop sooner, I can use a
sentinel on the finite one--but I'd rather ignore this variation for now).
I want to apply some function to the items from each iterator and then yield
the result--which suggests a third iterator.
I guess I wonder whether there's a pattern here that anyone has named--or if
there's a pattern that better expresses what I can only dimly see and
express. I have trouble naming things, so again, any tips on names is
helpful.
In the following, I would express weave_items with the following pseudo
code:
for item, alternate in iterator, alternator:
yield weave_item(item, alternate)
Instead, I have to explicitly call next(), which will raise StopIteration if
I happened to pass in an alternator with no args. Because I have no way (as
far as I can tell) of asking alternator, "Do you have any more bananas?"
That is, I can't peek into it (unless I wrap it in a class or something, I
suppose):
from __future__ import generators
def repeating_alternator(*args):
"""Return a repeating alternator for args."""
while args:
for a in args:
yield a
def weave_items(iterator, alternator, weave_item):
"""Iterate over iterator, applying weave_item to each item with its
pair in alternator.
"""
for item in iterator:
yield weave_item(item, alternator.next())
def color_item(item, color):
template = "<%(color)s>%(item)s</%(color)s>"
return template % locals()
Well, that was a bunch of poorly strung together thoughts. But it's late.
And just think, I squeezed all of this out of someone's question about how
they could squelch the "extra" space emitted by print foo<comma>. Perhaps
Liebniz was right.
Cheers,
// mark
-
More information about the Python-list
mailing list