Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Add proper dtype-support to np.flatiter #17981

Merged
merged 5 commits into from
Dec 11, 2020
Merged

Conversation

BvB93
Copy link
Member

@BvB93 BvB93 commented Dec 11, 2020

This PR adds proper dtype-support to np.flatiter.

The methods of the latter now successfully return an array/scalar of the appropriate dtype (when applicable).

Note that In order to get __array__ to work, the npt._SupportsArray protocol needed some minor restructuring,
the latter now only caring about the default value of its dtype parameter (i.e. dtype=None).
Concrete implementations of the protocol are responsible for adding any and all DTypeLike-based overloads.

Examples

Given the np.int64 array i8_array:

  • next(i8_array.flat) and i8_array.flat[0] are now inferred as np.int64.
  • i8_array.flat.__array__() is now inferred as np.ndarray[Any, np.dtype[np.int64]].

if TYPE_CHECKING or HAVE_PROTOCOL:
class _SupportsArray(Protocol):
@overload
Copy link
Member Author

Choose a reason for hiding this comment

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

Turns out the protocol already works fine for both positional-only and positional-or-keyword arguments, even without these overloads.

@overload
def __array__(self: flatiter[ndarray[Any, _DType]], __dtype: None = ...) -> ndarray[Any, _DType]: ...
@overload
def __array__(self, __dtype: DTypeLike) -> ndarray[Any, dtype[Any]]: ...
Copy link
Member Author

Choose a reason for hiding this comment

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

Adding overloads for all DTypeLike objects is quite frankly too much work.
For now just return dtype[Any] if a dtype-like object (besides None) is provided.

@BvB93 BvB93 changed the title ENH: Add proper dtype to np.flatiter ENH: Add proper dtype-support to np.flatiter Dec 11, 2020
Addresses numpy#17981 (comment)

Co-Authored-By: Charles Harris <charlesr.harris@gmail.com>
@charris charris merged commit cfb6a4d into numpy:master Dec 11, 2020
@charris
Copy link
Member

charris commented Dec 11, 2020

Thanks Bas.

@BvB93 BvB93 deleted the flatiter branch December 11, 2020 19:44
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.

None yet

2 participants