Skip to content

TYP: Covariant numpy.ndenumerate type parameter#26992

Merged
rgommers merged 1 commit intonumpy:mainfrom
jorenham:typing/ndenumerate
Jul 23, 2024
Merged

TYP: Covariant numpy.ndenumerate type parameter#26992
rgommers merged 1 commit intonumpy:mainfrom
jorenham:typing/ndenumerate

Conversation

@jorenham
Copy link
Member

Currently, the following code isn't accepted by typecheckers:

from typing import Any
import numpy as np

def ndmax_int(
    obj: np.ndenumerate[np.integer[Any]],
) -> tuple[tuple[int, ...], np.integer[Any]]:
    return max(obj)

x: np.ndenumerate[np.int_] = np.ndenumerate(np.arange(42))
ndmax_int(x)  # error

Pyright reports this error as follows:

Argument of type "ndenumerate[int_]" cannot be assigned to parameter "obj" of type "ndenumerate[integer[Any]]" in function "ndmax_int"
  "ndenumerate[int_]" is incompatible with "ndenumerate[integer[Any]]"
    Type parameter "_ScalarType@ndenumerate" is invariant, but "int_" is not the same as "integer[Any]"

This PR fixes this, by making _ScalarType@ndenumerate covariant.

@jorenham jorenham force-pushed the typing/ndenumerate branch from 3f8bbc9 to e029d35 Compare July 22, 2024 03:28
@rgommers rgommers added this to the 2.1.0 release milestone Jul 23, 2024
Copy link
Member

@rgommers rgommers left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mypy seems happy too, and this looks fine to me so let's give it a go. Thanks @jorenham!

@rgommers rgommers merged commit 22ca58a into numpy:main Jul 23, 2024
@jorenham jorenham deleted the typing/ndenumerate branch July 23, 2024 19:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants