switch recipe?

Mark McEahern marklists at mceahern.com
Fri Jul 12 18:11:59 EDT 2002


> Wouldn't you get exactly the same observable effect from
> the simpler function:
>
>  def make_switch(*args):
>       """Return an iterator that loops through args."""
>       if not args:
>           raise RuntimeError("Missing parameter: args.")
>       return iter(args)
>
> ...?

No, sadly.  The key to make_repeat() (as I've renamed it) is that it
repeatedly loops through args.  The above solution would suffice if you only
wanted to iterate over the set at most once.

Of course, I'm straining to come up with real world examples where this is
helpful, but I take that as a sign of my lack of imagination.  <wink>

In general, this recipe, if it's worthy to be called such, is useful when
you want to weave together a finite set of values of a given length (n) with
a different set of values of a different length (m) and for the i-th element
of n, you want it to be weaved with the len(m) modulo i-th element of m.

How's that for a fancy definition?

Of course, Alex, if there's a more elegant and simple way to do this, I have
no doubt you'll come up with it!

Cheers,

// mark

p.s.  for what it's worth, here's the latest code and demo:

#! /usr/bin/env python

from __future__ import generators

def make_repeat(*args):
    """Return a generator that repeatedly loops through args."""
    if not args:
        raise TypeError("make_repeat() takes at least one parameter.")
    def repeat():
        while args:
            for a in args:
                yield a
    return repeat()

def colorize(value, *colors):
    repeat = make_repeat(*colors)
    template = "<%(color)s>%(item)s</%(color)s>"
    items = []
    for item in value:
        color = repeat.next()
        formatted_item = template % locals()
        items.append(formatted_item)
    return ''.join(items)

s = colorize("testing", "black", "red", "green", "blue")
print s

expected = "<black>t</black>"\
           "<red>e</red>"\
           "<green>s</green>"\
           "<blue>t</blue>"\
           "<black>i</black>"\
           "<red>n</red>"\
           "<green>g</green>"

assert s == expected

-






More information about the Python-list mailing list