I have code that expects str
but will handle the case of being passed bytes
in the following way:
if isinstance(data, bytes):
data
There are two questions here, and the answers to them are different.
The first question, the title of this post, is What is the proper way to determine if an object is a bytes-like object in Python? This includes a number of built-in types (bytes
, bytearray
, array.array
, memoryview
, others?) and possibly also user-defined types. The best way I know of to check for these is to try to create a memoryview
out of them:
>>> memoryview(b"foo")
<memory at 0x7f7c43a70888>
>>> memoryview(u"foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: memoryview: a bytes-like object is required, not 'str'
In the body of the original post, though, it sounds like the question is instead How do I test whether an object supports decode()? @elizabeth-myers' above answer to this question is great. Note that not all bytes-like objects support decode().