I have code that expects str
but will handle the case of being passed bytes
in the following way:
if isinstance(data, bytes):
data
It depends what you want to solve. If you want to have the same code that converts both cases to a string, you can simply convert the type to bytes
first, and then decode. This way, it is a one-liner:
#!python3
b1 = b'123456'
b2 = bytearray(b'123456')
print(type(b1))
print(type(b2))
s1 = bytes(b1).decode('utf-8')
s2 = bytes(b2).decode('utf-8')
print(s1)
print(s2)
This way, the answer for you may be:
data = bytes(data).decode()
Anyway, I suggest to write 'utf-8'
explicitly to the decode, if you do not care to spare few bytes. The reason is that the next time you or someone else will read the source code, the situation will be more apparent.