[Tutor] Help with building bytearray arrays

Cameron Simpson cs at cskk.id.au
Mon Sep 10 18:07:44 EDT 2018


On 10Sep2018 10:23, Chip Wachob <wachobc at gmail.com> wrote:
>So, without all the fluff associated with wiggling lines, my function
>now looks like this:
>
>def RSI_size_the_loop():
>   results = []
>   all_together = []   # not certain if I need this, put it in in an
>attempt to fix the incompatibility if it existed

You don't need this. all_together doesn't need to be mentioned until you 
initiate it with your bytearray.join.

>   for x in range (0, MAX_LOOP_COUNT, slice_size):
>      results.append(my_transfer(disp, data_out, slice_size)
>
>      print " results ", x, " = ", results  # show how results grows
>on each iteration
>
>   all_together = bytearray().join(results)
>
>   print " all together ", all_together
>
>I can observe results increasing in size and the last time through the loop:
>
> results  48  =
>[[bytearray(b'\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
>[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
>[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')],
>[bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')]]

Peter has pointed out that you have a list of list-of-bytearray instead of a 
flat list-of-bytearray.

The inference here is that your my_transfer function is returning a single 
element list-of-bytearray.

>So, now when I hit the line:
>all_together = bytearray().join(results)
>
>I'm getting the Traceback :
[...]
>Traceback (most recent call last):
>  File "SW8T_5.py", line 101, in <module>      # this is my main script
>    loop_size = RSI_size_the_loop(Print)
>  File "/home/temp/Python_Scratch/examples/RSI.py", line 359, in
>RSI_size_the_loop
>    all_together = bytearray().join(results)
>TypeError: can only join an iterable of bytes (item 0 has type 'list')

So because you have a list-of-list, item[0] is indeed a list, not a bytearray.

If you change this:

  results.append(my_transfer(disp, data_out, slice_size)

into:

  result = my_transfer(disp, data_out, slice_size)
  print("result =", repr(result))
  results.append(result)

this should be apparent. So this issue lies with your my_transfer function; the 
main loop above now looks correct.

>I've even added in print statements for the types, so I could double
>check, and I get:
>
>results returns <type 'list'>
>all_together returns <type 'list'>
>
>So both are type 'list' which is referred to here :
>
>https://infohost.nmt.edu/tcc/help/pubs/python/web/sequence-types.html
>
>as a valid sequence type but apparently there's a detail I'm still missing...

Yeah. bytearray().join wants bytes or bytearrays in the list/iterable you hand 
it. You've got lists, with the bytearrays further in.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list