howto get itemsize of an array

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
rkompass
Posts: 66
Joined: Fri Sep 17, 2021 8:25 pm

howto get itemsize of an array

Post by rkompass » Tue Jul 26, 2022 3:20 pm

Hello,

I have an array like arr:

Code: Select all

from array import array
arr = array('b', (2,3,4,0))
Now only having arr, how can I get the itemsize of arr, which in this case is 1?
In Python 3.10 I would use

Code: Select all

arr.itemsize
Is there another way than str(arr) and extracting the code form the string "array('b', [2, 3, 4, 0])" ?

User avatar
scruss
Posts: 360
Joined: Sat Aug 12, 2017 2:27 pm
Location: Toronto, Canada
Contact:

Re: howto get itemsize of an array

Post by scruss » Tue Jul 26, 2022 6:15 pm

This is a bit of a hack and might create large objects that you don't want, but:

Code: Select all

len(arr.decode()) // len(arr)
returns the size of each element. Minimally tested ("seems to work with short arrays of b, i and q; good enough").

rkompass
Posts: 66
Joined: Fri Sep 17, 2021 8:25 pm

Re: howto get itemsize of an array

Post by rkompass » Tue Jul 26, 2022 8:38 pm

Thank you Scruss.
Didn't know of this solution. It's nice but will not work in my case unfortunately, as the array is possibly very large indeed.
I currently have:

Code: Select all

def array_dsize(arr):
    sizes = {'b': 0, 'B': 0, 'h':1, 'H':1, 'i':2, 'I':2, 'l':2, 'L':2, 'q':3, 'Q':3, 'f':2, 'd':3}
    baddr=bytes(array('O', [arr]))
    addr=int.from_bytes(baddr, 'little')
    ccode = chr(mem32[addr+4])
    if ccode in sizes:
        return sizes[ccode]
    else:
        raise ValueError('Unknown array format code')
but probably

Code: Select all

ccode=str(arr).split("'")[1].split("'")[0]
is better than the byte-poking there.
Apparently like with Pin, StateMachines and other objects: No pythonic straight methods to get the parameters.
A bit too minimalistic for my taste...

Post Reply