0

I want to let the typing check know that an object is a List[int], in PyCharm.

For example, I've got the following code:

def foo(a: List[int]):
  print(a)

arr = np.ndarray([1, 2, 3])
arr_list = arr.tolist()
foo(arr_list) # <-PyCharm warning

The warning says Expected type 'List[int]', got 'object' instead, since tolist typing hint returns object.

Is there any way to let the typing check know the typing of arr_list somehow, like assert all(isinstance(i,int) for i in arr_list), so that the warning goes away?

David Taub
  • 734
  • 1
  • 7
  • 27
  • 3
    Do you really want to have a runtime check of that just to silence lint? That's code that will need to execute every time your code is invoked. – Mattias Nilsson Feb 26 '22 at 13:48
  • How is `arr` defined? If I try this with `arr = array.array('i', [1,2,3])`, I don't get a type error (I'm not using pycharm; I'm running `mypy`, so if pycharm is using another type checker maybe it behaves differently). – larsks Feb 26 '22 at 13:49
  • 1
    If you're sure that `arr_list` is `list[int]`, consider using `typing.cast` https://docs.python.org/3/library/typing.html#typing.cast, e.g.: `arr_list = cast(list[int], arr.tolist())` – user2235698 Mar 08 '22 at 17:08
  • 2
    Some info about typing numpy arrays: https://stackoverflow.com/a/68132027/202168 https://github.com/numpy/numpy/issues/16544 – Anentropic Mar 09 '22 at 11:02

1 Answers1

2

Thanks for user2235698 for his tip. This solves the issue:

def foo(a: List[int]):
  print(a)

arr = np.ndarray([1, 2, 3])
arr_list = arr.tolist()

# this silences the warning
arr_list = typing.cast(List[int], arr_list)

foo(arr_list)
David Taub
  • 734
  • 1
  • 7
  • 27