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

后端 未结 7 1803
慢半拍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:26

    You can use:

    isinstance(data, (bytes, bytearray))
    

    Due to the different base class is used here.

    >>> bytes.__base__
    
    >>> bytearray.__base__
    
    

    To check bytes

    >>> by = bytes()
    >>> isinstance(by, basestring)
    True
    

    However,

    >>> buf = bytearray()
    >>> isinstance(buf, basestring)
    False
    

    The above codes are test under python 2.7

    Unfortunately, under python 3.4, they are same....

    >>> bytes.__base__
    
    >>> bytearray.__base__
    
    

提交回复
热议问题