How to check byte object?

Which test can determine if an object is a byte object ?

Typically, in some function calls, a string or object similar to a byte may be displayed. A simple but indirect solution in this context would be if not isinstance(obj, str).

I found ByteString in collections.abc. It seems to give the correct answers, but I'm not sure if this is the right way:

>>> import collections.abc as cabc
>>> isinstance(bytes(),cabc.ByteString)
True
>>> isinstance(bytearray(),cabc.ByteString)
True
>>> isinstance("string",cabc.ByteString)
False
+4
source share
1 answer

This is almost the right way, as collections.abc.ByteStringwell as typing.ByteStringrepresenting types bytes, bytearrayand memoryview, but not array.array, so you need another check

def IsBytesLike(obj):
    return isinstance(obj, typing.ByteString) or isinstance(obj, array.array)
0
source

Source: https://habr.com/ru/post/1680599/


All Articles