| Store | Cart

switch recipe?

From: Sean Shaleh Perry <shal...@attbi.com>
Fri, 12 Jul 2002 12:45:39 -0700 (PDT)
On 12-Jul-2002 Mark McEahern wrote:
> 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> > 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> 

out of curiosity, what happens when n reaches the end of the int/long/whatever
that stores it?

> 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:> 

while the above code is a nice sample, the below code should not be given to
people learning the language, it uses way too many tricks.  Plus one letter
variable names are a pain.

>   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")> 

switch is an interesting idea, definately needs a new name.

Recent Messages in this Thread
Mark McEahern Jul 12, 2002 07:15 pm
Sean Shaleh Perry Jul 12, 2002 07:45 pm
Messages in this thread