How should I annotate a function returning a ctypes array in Python?

Viewed 10423

Consider the following Python code:

def foo(aqs : typing.List[int]) -> ??? :
    array_type = ctypes.c_int64 * len(aqs)
    ans = array_type(*aqs)
    return ans

What's the correct annotation for the return value of this function? (In place of ???)

3 Answers

This function doesn't have a consistent return type, since the length of the returned array is part of the array's type. However, the type is always a subclass of ctypes.Array, which is the most specific annotation you can use:

def foo(aqs: List[int]) -> ctypes.Array:
    ...

Use python's built in List type List[T]

def foo(aqs : typing.List[int]) -> List[T]:
array_type = ctypes.c_int64 * len(aqs)
ans = array_type(*aqs)
return ans

Replace T with the list type

I'm new to Python, but it seems that typing.List[T] is what you're looking for (like @JörgBeyer said in its comment, above).

Example of a function that returns a List of instances of class RegistrationRequest :

import string
import typing
from datetime import datetime

from dataclasses import dataclass


@dataclass()
class RegistrationRequest:
    activity: string
    start_at: datetime


def registrations_requests() -> typing.List[RegistrationRequest]:
    return [
        RegistrationRequest('Zumba', datetime(2019, 6, 25, 12, 30, 0, 0)),
        RegistrationRequest('Zumba', datetime(2019, 6, 27, 19, 15, 0, 0)),
    ]


print('{0}'.format(registrations_requests()))

Output is:

[RegistrationRequest(activity='Zumba', start_at=datetime.datetime(2019, 6, 25, 12, 30)), RegistrationRequest(activity='Zumba', start_at=datetime.datetime(2019, 6, 27, 19, 15))]
Related