Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Superclass of bytes and bytearray?

I'm making a function which will accept either an Unicode string or a bytes (or bytearray) object. I want to make sure only those types get passed. I know I can check whether something is a string by doing isinstance(x, str), and I know I can write isinstance(x, bytes) or isinstance(x, bytearray).

Is there a more concise way to check the latter, i.e., is there a class from which both bytes and bytearray derive?

like image 257
Javier Avatar asked Jun 07 '11 21:06

Javier


2 Answers

There is no common base class except for object:

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

Don't check for the type. Let the user pass parameters of whatever type she desires. If the type does not have the required interface, your code will fail anyway.

like image 153
Sven Marnach Avatar answered Sep 30 '22 20:09

Sven Marnach


You can use:

isinstance(x, (bytes, bytearray))

However, duck typing might be useful, so other types not deriving from bytes or bytearray, but implementing the right methods could be passed to the function.

like image 30
Jasmijn Avatar answered Sep 30 '22 20:09

Jasmijn