
def tee(iterable): "Return two independent iterators from a single iterable" data = {} cnt = 0 def gen(next): global* cnt dpop = data.pop for i in count(): if i == cnt: item = data[i] = next() cnt += 1 else: item = dpop(i) yield item next = iter(iterable).next return (gen(next), gen(next))
which is IMO more readable.
it's a subtle piece of code. I wouldn't mind a more structured syntax with both the outer function declaring that is ok for some inner function to rebind some of its locals, and the inner function declaring that a local is coming from an outer scope:
def tee(iterable): "Return two independent iterators from a single iterable" data = {}
# cnt = 0 here would be ok
share cnt = 0: # the assignment is opt, # inner functions in the suite can rebind cnt def gen(next): use cnt # OR outer cnt dpop = data.pop for i in count(): if i == cnt: item = data[i] = next() cnt += 1 else: item = dpop(i) yield item
# cnt = 0 here would be ok
next = iter(iterable).next return (gen(next), gen(next))
yes it's heavy and unpythonic, but it makes very clear that something special is going on with cnt.
Might as well declare a class then. :-)
no time to add anything else to the thread.
Ditto. --Guido van Rossum (home page: http://www.python.org/~guido/)