switch recipe?
Tim Peters
tim.one at comcast.net
Fri Jul 12 21:47:17 EDT 2002
[Tim]
> 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.
[Mark McEahern]
> If you leave the while True, then it won't raise StopIteration
> when you call it without arguments.
So true -- and even if you change it to "while 1" <wink>.
> The simple fix is to replace that with while args.
Yes, that's nice!
> Here's the result of my latest tinkering. For what it's worth, I think I
> prefer raising the error in the generator when args is not specified
> rather than waiting until next() is called the first time--on the
> principle that raising the error earlier is better.
Then that's where we differ: I don't consider an empty sequence to be "an
error" in any sense of the word. For the same reason, range(10, 10) doesn't
complain in Python, or string[i:i], etc -- doing nothing gracefully is
important because there's sometimes nothing that needs be done <wink>.
More information about the Python-list
mailing list