Python Glossary Русский

Python 3.3+until 3.17collectionsterm

collections.abc.ByteString

collections.abc — protocols

Deprecated (removal in 3.17): a common type for bytes/bytearray. Use Buffer instead.

Syntax

isinstance(obj, collections.abc.ByteString)

The name oversells it: ByteString covers only bytes and bytearray, while memoryview and array do not match, so as an "any bytes" annotation it was always misleading. It has been deprecated since 3.12 and disappears in 3.17; write bytes | bytearray when you really mean those two types, or Buffer when any buffer-exposing object will do.

Examples

import collections.abc as abc
# ByteString объявлен устаревшим в 3.12 и будет удалён в 3.17; в 3.14 он ещё есть.
print(hasattr(abc, 'ByteString'))   # → True
# Замена — проверка по конкретным типам:
print(isinstance(b'x', (bytes, bytearray, memoryview)))   # → True
print(isinstance(bytearray(b'x'), (bytes, bytearray, memoryview)))   # → True
print(isinstance(memoryview(b'x'), (bytes, bytearray, memoryview)))   # → True
print(isinstance('x', (bytes, bytearray, memoryview)))   # → False
# Python 3.12+
import collections.abc as abc
# Либо abc.Buffer (появился в 3.12) — он про поддержку буферного протокола:
print(isinstance(b'x', abc.Buffer))   # → True
print(isinstance('x', abc.Buffer))   # → False
# Python 3.17+
from collections.abc import Buffer
def size(data: Buffer) -> int:   # вместо ByteString в аннотации
    return len(memoryview(data))
print(size(b'ab'), size(bytearray(3)), size(memoryview(b'xyz')))   # → 2 3 3

See also

Open in the full glossarydocs.python.orgReport an inaccuracy