Skip to content

Commit 804dfa1

Browse files
committed
pythongh-91896: Deprecate collections.abc.ByteString
Getting a DeprecationWarning on issubclass proved to be difficult, because it could affect unrelated looking things like `isinstance(bytes, Sequence)`
1 parent 244d4cd commit 804dfa1

File tree

2 files changed

+32
-7
lines changed

2 files changed

+32
-7
lines changed

Lib/_collections_abc.py

+21-3
Original file line numberDiff line numberDiff line change
@@ -1064,8 +1064,27 @@ def count(self, value):
10641064
Sequence.register(range)
10651065
Sequence.register(memoryview)
10661066

1067-
1068-
class ByteString(Sequence):
1067+
class _DeprecateByteStringMeta(ABCMeta):
1068+
def __new__(cls, name, bases, namespace, **kwargs):
1069+
if name != "ByteString":
1070+
import warnings
1071+
1072+
warnings._deprecated(
1073+
"collections.abc.ByteString",
1074+
remove=(3, 14),
1075+
)
1076+
return super().__new__(cls, name, bases, namespace, **kwargs)
1077+
1078+
def __instancecheck__(cls, instance):
1079+
import warnings
1080+
1081+
warnings._deprecated(
1082+
"collections.abc.ByteString",
1083+
remove=(3, 14),
1084+
)
1085+
return super().__instancecheck__(instance)
1086+
1087+
class ByteString(Sequence, metaclass=_DeprecateByteStringMeta):
10691088
"""This unifies bytes and bytearray.
10701089
10711090
XXX Should add all their methods.
@@ -1076,7 +1095,6 @@ class ByteString(Sequence):
10761095
ByteString.register(bytes)
10771096
ByteString.register(bytearray)
10781097

1079-
10801098
class MutableSequence(Sequence):
10811099
"""All the operations on a read-write sequence.
10821100

Lib/test/test_collections.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -1940,14 +1940,21 @@ def assert_index_same(seq1, seq2, index_args):
19401940

19411941
def test_ByteString(self):
19421942
for sample in [bytes, bytearray]:
1943-
self.assertIsInstance(sample(), ByteString)
1943+
with self.assertWarns(DeprecationWarning):
1944+
self.assertIsInstance(sample(), ByteString)
19441945
self.assertTrue(issubclass(sample, ByteString))
19451946
for sample in [str, list, tuple]:
1946-
self.assertNotIsInstance(sample(), ByteString)
1947+
with self.assertWarns(DeprecationWarning):
1948+
self.assertNotIsInstance(sample(), ByteString)
19471949
self.assertFalse(issubclass(sample, ByteString))
1948-
self.assertNotIsInstance(memoryview(b""), ByteString)
1950+
with self.assertWarns(DeprecationWarning):
1951+
self.assertNotIsInstance(memoryview(b""), ByteString)
19491952
self.assertFalse(issubclass(memoryview, ByteString))
1950-
self.validate_abstract_methods(ByteString, '__getitem__', '__len__')
1953+
with self.assertWarns(DeprecationWarning):
1954+
self.validate_abstract_methods(ByteString, '__getitem__', '__len__')
1955+
1956+
with self.assertWarns(DeprecationWarning):
1957+
class X(ByteString): pass
19511958

19521959
def test_MutableSequence(self):
19531960
for sample in [tuple, str, bytes]:

0 commit comments

Comments
 (0)