switch recipe?

Tim Peters tim.one at comcast.net
Fri Jul 12 18:17:59 EDT 2002


[Cliff Wells (I think)]
>  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

[Alex Martelli]
> 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)

The top one generates an unbounded sequence, due to the "while True".  The
Icon language calls this "repeated alternation", and actually has a prefix
operator for it (the vertical bar).

What I'm unclear about is why we're writing a function to return a generator
function:  why not write a generator function directly?  So my candidate for
simplification is:

def make_switch(*args):
    """Generate the elements in args repeatedly."""
    if not args:
        raise TypeError("at least one argument required")
    while True:
        for a in args:
            yield a

I'd lose the "if not args:" block, though; if the arglist is empty, it will
simply terminate without yielding anything, and that's what I expect the
empty case to do.






More information about the Python-list mailing list