Search code examples
pythonpycharmpython-typing

How do I let the typing check know an object is List[int]?


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?


Solution

  • 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)