[Python-Dev] question about PEP 323 (copyable iterators)
Andrew Koenig
ark at acm.org
Tue Nov 11 10:48:15 EST 2003
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!]
else:
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:
class enumerate(object):
def __init__(self, it):
self.it = iter(it)
self.i = -1
# next and __iter__ methods snipped from the original
def __copy__(self):
result = self.__class__.new()
result.it = self.it.__copy__()
result.i = self.i
return result
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:
class enumerate(object):
def __init__(self, it):
self.it = iter(it)
self.i = -1
try it.__copy__
except AttributeError: pass
else: self.__copy__ = self.conditional_copy
def conditional_copy(self):
result = self.__class__.new()
result.it = self.it.__copy__()
result.i = self.i
return result
Am I missing something?
More information about the Python-Dev
mailing list