pythonpython-multiprocessingpython-typing

python multiprocessing.Array typing


When creating an array, I want to put it inside a dataclass, but I cannot find the type of the returned object.

arr = multiprocessing.RawArray("i", 2)

If I do:

>>> type(arr)
<class 'multiprocessing.sharedctypes.c_long_Array_2'>

but multiprocessing.sharedctypes.c_long_Array_2 does not exists.
How can I use type hints, e.g arr: the_type with multiprocessing Array?

UPDATE
Pycharm example when using typing ctypes.c_long * 2, there's still a value attribute which is invalid.

enter image description here


Solution

  • The shared array's type is derived from the ctypes module. You could also perhaps use this module to help you be more explicit about the data type of the array:

    import multiprocessing
    import ctypes # This is what you're looking for
    
    # Your function that you want to type-hint for
    def func(arr: ctypes.c_long * 2):
        # Some operations
        ...
    
    # Being explicit about which c-type i want my array to be
    arr = multiprocessing.RawArray(ctypes.c_long, 2)
    
    # This evaluates to true
    print(isinstance(arr, ctypes.c_long * 2))
    

    Note: ctypes does not come with all the possibilities of array sizes so notice the ctypes.c_long * 2 syntax to indicate that it is an array of long of size = 2.