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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With