What is the proper way to determine if an object is a bytes-like object in Python?

后端 未结 7 1801
慢半拍i
慢半拍i 2021-01-30 09:40

I have code that expects str but will handle the case of being passed bytes in the following way:

if isinstance(data, bytes):
    data          


        
相关标签:
7条回答
  • 2021-01-30 10:42

    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().

    0 讨论(0)
提交回复
热议问题