Superclass of bytes and bytes?

I am creating a function that will accept either a Unicode string or a byte object (or bytearray). I want to make sure that only those types are passed. I know that I can check if there is something string by running isinstance(x, str) , and I know that I can write isinstance(x, bytes) or isinstance(x, bytearray) .

Is there a shorter way to check for the latter, i.e. Is there a class from which both bytes and bytearray ?

+6
source share
3 answers

There is no common base class except object :

 >>> bytearray.__base__ <class 'object'> >>> bytes.__base__ <class 'object'> 

Do not check type. Let the user pass parameters of any type that she wants. If the type does not have the required interface, your code will fail anyway.

+6
source

You can use:

 isinstance(x, (bytes, bytearray)) 

However, duck typing can be useful, so other types are not related to bytes or bytearray, but the implementation of the correct methods can be passed to the function.

+2
source

It makes no sense to accept Unicode strings, since they are by no means binary data. I would probably agree with some sequence and raise an error if any element in this sequence is not an integer from 0 to 255 (which you will probably find during compression).

If you want to support Python 2, you also need to accept strings as a special case, since it is a binary type for Python 2.

+2
source

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


All Articles