switch recipe?

Mark McEahern marklists at mceahern.com
Fri Jul 12 17:32:35 EDT 2002


[Chris Liechti]
> > Is switch a bad name for this?
>
> definetly yes ;-) as a C programmer, i expect something completly
> different... (switch() {case x:})
>
> > Can anyone suggest a better name?
>
> how about "repeat"? 'cause that's what it does.

I like repeat().  That is, I like repeat!  <wink>  Thanks!

> isn't this simpler, more obvious what it does, and still doing what you
> want:
>
> >>> from __future__ import generators
> >>> def repeat(*args):
> ... 	if not args: args = [None]    	#optionaly to catch empty args
> ... 	while 1:
> ... 		for x in args: yield x
> ...
> >>> zip(range(10), repeat('even', 'odd'))
> [(0, 'even'), (1, 'odd'), (2, 'even'), (3, 'odd'), (4, 'even'),
> (5, 'odd'),
> (6, 'even'), (7, 'odd'), (8, 'even'), (9, 'odd')]
> >>>

Yes, that's very nice.  Here's the latest, with the help of all the
suggestions I've gotten.

#! /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