[Python-Dev] question about PEP 323 (copyable iterators)
aleaxit at yahoo.com
Tue Nov 11 12:21:53 EST 2003
On Tuesday 11 November 2003 04:48 pm, Andrew Koenig wrote:
> Early in PEP 323, there is a claim that an iterator is considered copyable
> if it has a __copy__ method. The following example in the PEP illustrates
> that claim:
> def tee(it):
> it = iter(it)
> try: copier = it.__copy__
> except AttributeError:
> # non-copyable iterator, do all the needed hard work
> # [snipped!]
> return it, copier()
> Later in the PEP, there is an example that suggests that an iterator should
> be considered copyable only if its __copy__ method can be called:
Very good point -- thanks!
> Here, class enumerate always has a __copy__ method, even if the iterator
> that is being enumerated doesn't. In other words, if you use class
> enumerate on an iterator that isn't copyable, you get an iterator with a
> __copy__ method that isn't copyable.
> Is that behavior really right? I would think that you would have to do
> something like this:
Special methods are normally defined on the type, not on the instance.
So, a per-instance conditional definition of __copy__ does not appear
to be right. Rather, I think I should rework the above example as:
it = iter(it)
try: return it, it.__copy__()
except (AttributeError, TypeError):
# non-copyable iterator, do all the needed hard work
i.e., an iterator is copyable if it has a __copy__ method that can be
called without arguments and won't raise AttributeError or TypeError
(other exceptions are not expected and would therefore propagate).
This will allow "wrappers" such as enumerate to do their job most
simply. (We could allow only TypeError and not AttributeError, but
that would complicate both suppliers of __copy__ such as enumerate
and consumers of it such as tee).
More information about the Python-Dev