Here is an MRE you can run on mypy Playground:
import ctypes
import numpy as np # type: ignore # (no stubs for numpy)
def np_to_c(arr: np.ndarray) -> tuple[ctypes.POINTER(ctypes.c_int), ctypes.c_int]:
return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), ctypes.c_int(len(arr))
This type hinting is wrong and according to mypy:
main.py:4: error: Invalid type comment or annotation [valid-type]
main.py:4: note: Suggestion: use ctypes.POINTER[...] instead of ctypes.POINTER(...)
Found 1 error in 1 file (checked 1 source file)
but when I do use ctypes.POINTER[...] instead of ctypes.POINTER(...) (cf screenshot below), I get:
main.py:4: error: Function "ctypes.POINTER" is not valid as a type [valid-type]
main.py:4: note: Perhaps you need "Callable[...]" or a callback protocol?
Found 1 error in 1 file (checked 1 source file)

You could use a different definition specifically when running type checking:
import ctypes
from typing import TYPE_CHECKING
import numpy as np # type: ignore # (no stubs for numpy)
if TYPE_CHECKING:
IntPointer = ctypes._Pointer[ctypes.c_int]
else:
IntPointer = ctypes.POINTER(ctypes.c_int)
def np_to_c(arr: np.ndarray) -> tuple[IntPointer, ctypes.c_int]:
return arr.ctypes.data_as(IntPointer), ctypes.c_int(len(arr))
Try me on mypy-play
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With