Skip to content

Commit

Permalink
pythongh-91896: Deprecate collections.abc.ByteString
Browse files Browse the repository at this point in the history
Getting a DeprecationWarning on issubclass proved to be difficult,
because it could affect unrelated looking things like
`isinstance(bytes, Sequence)`
  • Loading branch information
hauntsaninja committed Feb 21, 2023
1 parent 244d4cd commit 804dfa1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
24 changes: 21 additions & 3 deletions Lib/_collections_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1064,8 +1064,27 @@ def count(self, value):
Sequence.register(range)
Sequence.register(memoryview)


class ByteString(Sequence):
class _DeprecateByteStringMeta(ABCMeta):
def __new__(cls, name, bases, namespace, **kwargs):
if name != "ByteString":
import warnings

warnings._deprecated(
"collections.abc.ByteString",
remove=(3, 14),
)
return super().__new__(cls, name, bases, namespace, **kwargs)

def __instancecheck__(cls, instance):
import warnings

warnings._deprecated(
"collections.abc.ByteString",
remove=(3, 14),
)
return super().__instancecheck__(instance)

class ByteString(Sequence, metaclass=_DeprecateByteStringMeta):
"""This unifies bytes and bytearray.
XXX Should add all their methods.
Expand All @@ -1076,7 +1095,6 @@ class ByteString(Sequence):
ByteString.register(bytes)
ByteString.register(bytearray)


class MutableSequence(Sequence):
"""All the operations on a read-write sequence.
Expand Down
15 changes: 11 additions & 4 deletions Lib/test/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -1940,14 +1940,21 @@ def assert_index_same(seq1, seq2, index_args):

def test_ByteString(self):
for sample in [bytes, bytearray]:
self.assertIsInstance(sample(), ByteString)
with self.assertWarns(DeprecationWarning):
self.assertIsInstance(sample(), ByteString)
self.assertTrue(issubclass(sample, ByteString))
for sample in [str, list, tuple]:
self.assertNotIsInstance(sample(), ByteString)
with self.assertWarns(DeprecationWarning):
self.assertNotIsInstance(sample(), ByteString)
self.assertFalse(issubclass(sample, ByteString))
self.assertNotIsInstance(memoryview(b""), ByteString)
with self.assertWarns(DeprecationWarning):
self.assertNotIsInstance(memoryview(b""), ByteString)
self.assertFalse(issubclass(memoryview, ByteString))
self.validate_abstract_methods(ByteString, '__getitem__', '__len__')
with self.assertWarns(DeprecationWarning):
self.validate_abstract_methods(ByteString, '__getitem__', '__len__')

with self.assertWarns(DeprecationWarning):
class X(ByteString): pass

def test_MutableSequence(self):
for sample in [tuple, str, bytes]:
Expand Down

0 comments on commit 804dfa1

Please sign in to comment.