Skip to content

TYP: mypy often infers type Any for overloaded operators (example: __add__ vs np.add) #22064

Closed
@hhoppe

Description

@hhoppe

Describe the issue:

I'm trying to use typed np.ndarray with mypy.
I find many cases where computations involving np.ndarray eventually become type Any.
I am not certain if the fault lies in numpy or in mypy.

One obvious example is that a.__add__(b) behaves differently from np.add(a, b), as in the following code example.

In the final line, even when starting with a typed array b (numpy.ndarray[Any, numpy.dtype[numpy.floating[numpy.typing._64Bit]]]), the computation np.add(b, b) + np.add(b, b) produces Any.

Reproduce the code example:

import numpy as np
from typing import Any

def function(a: np.ndarray[Any, Any]) -> None:
  b = np.ones(10)

  reveal_type(a)  # numpy.ndarray[Any, Any]
  d1 = a + a
  d1b = a.__add__(a)
  d2 = np.add(a, a)
  reveal_type(d1)  # Any
  reveal_type(d1b)  # Any
  reveal_type(d2)  # numpy.ndarray[Any, numpy.dtype[Any]]

  reveal_type(b)  # numpy.ndarray[Any, numpy.dtype[numpy.floating[numpy.typing._64Bit]]]
  d3 = b + b
  d4 = np.add(b, b)
  reveal_type(d3)  # numpy.ndarray[Any, numpy.dtype[numpy.floating[Any]]]
  reveal_type(d4)  # numpy.ndarray[Any, numpy.dtype[Any]]

  reveal_type(d3)  # numpy.ndarray[Any, numpy.dtype[numpy.floating[Any]]]
  d5 = d3 + d3
  d6 = np.add(d3, d3)
  reveal_type(d5)  # numpy.ndarray[Any, Any]
  reveal_type(d6)  # numpy.ndarray[Any, numpy.dtype[Any]]

  reveal_type(d4)  # numpy.ndarray[Any, numpy.dtype[Any]]
  d7 = d4 + d4
  d8 = np.add(d4, d4)
  reveal_type(d7)  # Any
  reveal_type(d8)  # numpy.ndarray[Any, numpy.dtype[Any]]

  reveal_type(np.add(b, b) + np.add(b, b))  # Any !

Error message:

No response

NumPy/Python version information:

1.22.4 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0]

mypy==0.971
mypy-extensions==0.4.3
either numpy==1.22.4 or numpy==1.23.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions