35

In Python 3 I'm getting error TypeError: a bytes-like object is required, not 'bytearray'

I have a bytearray, which looks like this:

print(my_ba)     # bytearray(b'}\x0e\x15/ow4|-')

If I enter this in the console it works:

>>> print(base58.b58encode(b'}\x0e\x15/ow4|-'))
2bKmhuGiGP7t8

But this gives an error, and I can't find out how to get the b'' string from the bytearray:

>>> print(base58.b58encode(my_ba))
TypeError: a bytes-like object is required, not 'bytearray'

I'm sure it's obvious, but how do I convert the bytearray to a string with a b prefix?

3
  • 3
    print(base58.b58encode(bytes(my_ba)) - just convert it
    – cs95
    Commented Sep 5, 2017 at 22:18
  • 1
    A bytearray is a bytes-like object, but the library you're using has an unnecessarily restrictive implementation and a misleading error message. Commented Sep 5, 2017 at 22:24
  • @user2357112, incidentally i ran into the same bytes parameter restriction within the stdlib zlib.decompress method
    – iruvar
    Commented Aug 28, 2019 at 16:22

3 Answers 3

68

As Coldspeed put it in the comments, just pass a bytearray to a bytes call:

bytes(my_ba)

2

Concatenation between bytes and bytearray takes the type of the first item, so concatenating a bytearray to an empty byte string also converts it into bytes.

my_ba = bytearray(b'}\x0e\x15/ow4|-')
my_ba = b"" + my_ba
print(type(my_ba))    # <class 'bytes'>

With that being said, this error probably doesn't show up in the recent versions of whatever library you're using because bytearray is a bytes-like type. For example, base58 accepts bytearray as is since version 1.0.3..

2

This was a bug.

It was fixed in version 2.0.0 of base58, released in January 2020.


And of course, as previously noted, the workaround you can apply when this happens in other situations is just "casting" to bytes:

buggy_function(bytes(my_byteslike))

Note: this has the overhead of copying all the data, when the data isn't already exactly the bytes type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.