EDIT: could it be that this is just an oversight that has not been addressed? The standard types documentation includes .copy()
and .clear()
in the table of methods for mutable sequence types.
I noticed something a little curious this morning: the list
object in Python >3.3 includes a .copy()
method, and also a .clear()
method. However the collections.abc
Sequence
and MutableSequence
abstract base classes do not include these methods are part of their spec (.clear()
would only make sense as part of the MS spec, of course).
>>> x = [1,2,3]
>>> x.copy()
[1, 2, 3]
>>> x.clear()
>>> x
[]
My understanding is that part of the reason to use MutableSequence
is to signal to the universe you want your object to "act like a list
" (unless clearly stated otherwise):
from typing import Sequence
class S(Sequence):
x = [1, 2, 3]
def __getitem__(self, item):
return self.x[item]
def __len__(self):
return len(self.x)
Yet a fully defined S type cannot be copied (and a MS cannot be cleared) like a list
:
>>> s = S()
>>> s.copy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'S' object has no attribute 'copy'
This seems weird and as with most things like this, there's probably a good reason for it. What is it?