Skip to content

TYP: nditer does not allow None-valued elements in operand sequence #28038

@simonaltrogge

Description

@simonaltrogge

Describe the issue:

Passing None-valued elements next to array_like-valued elements in a sequence as operands to nditer is part of the documented idiom of iterator-allocated output arrays. Mentions of this can also be found in the documentation of nditer directly. The type-hints do not reflect this, however, and lead to an error instead when using this intended way of calling nditer.

Reproduce the code example:

import numpy as np
import numpy.typing as npt

def square(a: npt.NDArray):
    with np.nditer([a, None]) as it:
        for x, y in it:
            y[...] = x*x
        return it.operands[1]

Error message:

Argument of type "list[NDArray[Unknown] | None]" cannot be assigned to parameter "op" of type "ArrayLike | Sequence[ArrayLike]" in function "__new__"
  Type "None" is not assignable to type "ArrayLike"
    "None" is incompatible with protocol "Buffer"
      "__buffer__" is not present
    "None" is incompatible with protocol "_SupportsArray[dtype[Any]]"
      "__array__" is not present
    "None" is incompatible with protocol "_NestedSequence[_SupportsArray[dtype[Any]]]"
      "__len__" is not present
      "__getitem__" is not present Pylance (reportArgumentType)

Python and NumPy Versions:

2.2.0
3.13.1 | packaged by conda-forge | (main, Dec 5 2024, 21:23:54) [GCC 13.3.0]

Type-checker version and settings:

Pylance 2024.12.1 used in Visual Studio Code 1.96.0

Additional typing packages.

No response

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