[Python-Dev] RE: cloning iterators again

Alex Martelli aleaxit at yahoo.com
Mon Oct 27 10:24:01 EST 2003

On Monday 27 October 2003 03:53 pm, Guido van Rossum wrote:
> > But I don't understand how it would be quite messy to take advantage
> > of this in tee(), either: simply, tee() would start with the equivalent
> > of it = iter(it)
> >     try: return it, copy.copy(it)
> >     except TypeError:pass
> > and proceed just like now if this shortcut hasn't worked -- that's all.
> Right, that's what the tee() at the end of my code did, except it
> checked for __copy__ explicitly, since I assume that only iterators
> whose author has thought about copyability should be assumed copyable;
> this means that the default copy stategy for class instances (classic
> and new-style) as suspect.

I see!  So you want to be more prudent here than an ordinary copy
would be, and also disallow alternatives to __copy__ such as
__getinitargs__ or __getstate__/__setstate__ ...?  Could you give
an example of an iterator class, which is "accidentally" copyable, but
"shouldn't" be for purposes of tee only?  I have a hard time thinking
of any (hmmm, perhaps a file object that's not "held" directly as an
attribute, but indirectly in some devious way...?).  Maybe I need to
revise the PEP 323, which I just committed (to nondist/peps as usual)

> tee is more and less powerful than copy; it is more powerful because
> it works for any iterator, but less so because you can't continue
> using the underlying iterator (any calls to its next() method will be
> lost for both tee'ed copies).

Yes, it IS worth pointing out that the idiom for using tee must
always be
    a, b = tee(c)
and c is not to be used afterwards -- or equivalently
    a, b = tee(a)
when, as common, there are no other references to a (even
indirectly e.g. via somebody holding on to a ref to a.next).  Hmmm,
I wonder if that should go in my PEP, though, since it's more about tee
than about copy...?


More information about the Python-Dev mailing list