0

This snipped thorws an error, I couldn't find a solution so far.

from array import array
arr = array('B',[8, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 2])
ab = arr.tobytes()
array.frombytes(ab)
TypeError                                 Traceback (most recent call last)
Cell In[117], line 4
      2 arr = array('B',[8, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 2])
      3 ab = arr.tobytes()
----> 4 array.frombytes(ab)

TypeError: descriptor 'frombytes' for 'array.array' objects doesn't apply to a 'bytes' object

I treid this in Python 3.10.8 and a fresh 3.11.0 environment. No luck with neither

6
  • 1
    The frombytes method defined in the array class is an ordinary instance method, not a classmethod or staticmethod. It needs to be called on an instance of the class. Calling it from the class itself like this means that ab will be used as self, which doesn't work. The linked duplicate is the most popular I could find on this theme; I will keep looking for a more general canonical. Commented Jan 20, 2023 at 11:14
  • Does this answer your question? Convert bytearray to array.array('B') Commented Jan 20, 2023 at 11:27
  • Thank you both. @KarlKnechtel, yes, this is exactly the problem. Corralien's solution, by first building a new array of the same type and then using the method, works as expected. Commented Jan 20, 2023 at 12:28
  • What a terrible error message. If @karl is correct, the message should say something like "could not call frombytes on object <class bytes>" to tell you first param is wrong type. Instead we get nonsense that says frombytes (b'') doesn't apply to a bytes object, which is the whole point of frombytes. Commented Aug 12 at 10:25
  • @Ed_ I think it's rather the design that's poor. Conventionally, fromwhatever methods are supposed to be classmethods, since conventionally the purpose is to create an instance. See for example int.from_bytes. Commented Aug 12 at 13:30

1 Answer 1

1

You have to build another array before receive data frombytes:

from array import array
arr = array('B',[8, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 2])
ab = arr.tobytes()

arr1 = array('B')
arr1.frombytes(ab)

Output:

>>> arr1
array('B', [8, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 2])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.