Search code examples
pythonnumpypython-typingpyright

Why can't I pass a variable of type `NDArray` to `np.save`?


I turned strict type checking on for Pylance in VSCode and it's complaining about the following snippet:

import numpy as np
from numpy.typing import NDArray

this_seems_to_be_causing_the_issue: NDArray[np.float32] = np.array([1,2,3], dtype=np.float32)
np.save("i_think_anything_can_go_here", this_seems_to_be_causing_the_issue)

I get the following warning/error:

Type of "save" is partially unknown
  Type of "save" is "(file: str | PathLike[str] | _SupportsWrite[bytes], arr: _SupportsArray[dtype[Unknown]] | _NestedSequence[_SupportsArray[dtype[Unknown]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], allow_pickle: bool = ..., fix_imports: bool = ...) -> None"

Am I doing something wrong, or is this a bug / limitation in Pylance / numpy / something else? Is there a way to fix this?

At first I encountered this issue with NDArray[Any], and thought the Any might be the issue, but a more specific type results in an identical warning. Removing the type hint doesn't help either. Don't know how to debug from here.

I have Python version 3.10.12, numpy version 1.23.5, and Pylance extension version v2023.9.20.


Solution

  • It was a numpy issue as I fixed it by upgrading numpy. More specifically there's no warning starting from version 1.24.2, and this particular commit was the fix: https://github.com/numpy/numpy/pull/23150.