In response to a question earlier today, I wrote a function I called
make_color_switch:
from __future__ import generators
def make_color_switch(color1, color2):
def color_switch():
i = 0
while True:
if i % 2:
yield color2
else:
yield color1
i += 1
return color_switch
It seemed like this could be more generic:
from __future__ import generators
def make_switch(*args):
"""Return a generator that loops through args."""
if not args:
raise RuntimeError("Missing parameter: args.")
def switch():
i = n = 0
while True:
i = n % len(args)
yield args[i]
n += 1
return switch
Is switch a bad name for this? Can anyone suggest a better name? Other
improvements? What I like about this code is it demonstrates several
"advanced" features of Python, all the while retaining (imho) the simplicity
and clarity Python is known for:
generators
nested scopes
variable length argument arrays
functions as objects
Here's sample code that shows it used in the context of the original
question:
#! /usr/bin/env python
from __future__ import generators
def make_switch(*args):
"""Return a generator that loops through args."""
if not args:
raise RuntimeError("Missing parameter: args.")
def switch():
i = n = 0
while True:
i = n % len(args)
yield args[i]
n += 1
return switch
def colorize(s, *colors):
switch = make_switch(*colors)()
template = "<%(color)s><b>%(c)s</b></color>"
l = []
for c in s:
color = switch.next()
l.append(template % locals())
print ''.join(l)
colorize("testing", "black", "red", "green", "blue")
Is make_switch useful enough to post as a recipe? I didn't search to see
whether someone has already made something like this. It seems at once both
trivial and reuseful.
Cheers,
// mark
-