switch recipe?

Alex Martelli aleax at aleax.it
Fri Jul 12 17:58:45 EDT 2002


Alex Martelli wrote:

> Mark McEahern wrote:
> 
>>> or possibly:
>>> 
>>>  def make_switch(*args):
>>>       """Return a generator that loops through args."""
>>>       if not args:
>>>           raise RuntimeError("Missing parameter: args.")
>>>       def switch():
>>>           while True:
>>>               for a in args:
>>>                  yield a
>>>       return switch
>> 
>> Holy cow, that's much nicer!
> 
> 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)

...and the answer is "no", because the first function returns an
unbounded iterator, looping around the args forever, while the
second one returns a bounded iterator, looping around the
args just once.  I don't think there's any substantially simpler
way to obtain the first function's effect.


Alex





More information about the Python-list mailing list