switch recipe?

Mark McEahern marklists at mceahern.com
Fri Jul 12 16:35:53 EDT 2002


> Or you could just change it to (untested):
>
> def make_color_switch(color1, color2):
>       def color_switch():
>           i = 0
>           while True:
>               if i:
>                   yield color2
>               else:
>                   yield color1
>               i = not i
>       return color_switch

Nice.  I guess I'm still not too worried about n maxing out.  Don't ints
just spill into longs go on forever?  Nevertheless, for the generic loop,
your suggestion makes me realize we can just dispense with n altogether:

  def make_loop(*args):
      """Return a generator that loops through args."""
      if not args:
          raise RuntimeError("Missing parameter: args.")
      def loop():
          i = 0
          while True:
              i = i % len(args)
              yield args[i]
              i += 1
      return loop

This way, the counter never gets bigger than len(args).  <wink>

// m

-






More information about the Python-list mailing list