switch recipe?
Chris Liechti
cliechti at gmx.net
Fri Jul 12 17:21:32 EDT 2002
"Mark McEahern" <mark at mceahern.com> wrote in
news:mailman.1026501403.17010.python-list at python.org:
> from __future__ import generators
>
> def make_switch(*args):
> """Return a generator that loops through args."""
> if not args:
> raise RuntimeError("Missing parameter: args.")
this should be a TypeError, as the builtins raise that too
raise TypeError("switch() takes at least one argument")
> def switch():
> i = n = 0
> while True:
> i = n % len(args)
> yield args[i]
> n += 1
> return switch
>
> Is switch a bad name for this?
definetly yes ;-) as a C programmer, i expect something completly
different... (switch() {case x:})
> Can anyone suggest a better name?
how about "repeat"? 'cause that's what it does.
> Other improvements?
isn't this simpler, more obvious what it does, and still doing what you
want:
>>> from __future__ import generators
>>> def repeat(*args):
... if not args: args = [None] #optionaly to catch empty args
... while 1:
... for x in args: yield x
...
>>> zip(range(10), repeat('even', 'odd'))
[(0, 'even'), (1, 'odd'), (2, 'even'), (3, 'odd'), (4, 'even'), (5, 'odd'),
(6, 'even'), (7, 'odd'), (8, 'even'), (9, 'odd')]
>>>
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list