[Python-Dev] copying of itertools iterators

Andrew Svetlov andrew.svetlov at gmail.com
Fri Apr 2 01:20:33 CEST 2010


using of copy.copy for simple iterators is forbidden

>>> import copy
>>> copy.copy(iter([1, 2, 3]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/andrew/projects/py3k/Lib/copy.py", line 96, in copy
    return _reconstruct(x, rv, 0)
  File "/home/andrew/projects/py3k/Lib/copy.py", line 284, in _reconstruct
    y = callable(*args)
  File "/home/andrew/projects/py3k/Lib/copyreg.py", line 88, in __newobj__
    return cls.__new__(cls, *args)
TypeError: object.__new__(list_iterator) is not safe, use
list_iterator.__new__()

That behavior is safe and clean.
But it's possible to copy iterator objects returned by itertools functions:

>>> i = itertools.chain([1, 2], [3, 4, 5])
>>> i.__next__()
1
>>> j = copy.copy(i)
>>> j.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> i.__next__()
2

Looks like itertools object should be protected from usage like that.
Folks, what are you think about?


More information about the Python-Dev mailing list