Skip to content

astype(copy=False) is ambiguous when only changing signedness #867

Closed as not planned

Description

@crusaderky

XREFs

astype specifies:

copy (bool) – specifies whether to copy an array when the specified dtype matches the data type of the input array x. If True, a newly allocated array must always be returned. If False and the specified dtype matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned. Default: True.

I think that the definition of copy=False is unclear when two dtypes only differ in signedness (e.g. int64 vs uint64) so one could be a view of the other. This is particularly true if you consider that astype has no option for elementwise validation vs. over/underflow.

"A newly allocated array" could be interpreted either as

  • new python object around a new (deep-copied) buffer, OR
  • new python object, possibly pointing to the same buffer (a "view" in numpy speech).

In numpy, astype unnecessarily deep-copies. I suggested changing its behaviour at numpy/numpy#27509 but the feedback was that the behaviour of numpy is unlikely to change as it would be a breaking change. However, there is no reason why other libraries ascribing to the array API would need to replicate numpy's behaviour.

My proposal here is to add a clause

If False and the specified dtype matches the data type of the input array, the input array must be returned; otherwise, a newly allocated array must be returned, which may or may not share memory with the input array.

Activity

  1. kgryte commented on Jan 23, 2025

    @kgryte
    Contributor

    Related: #266

  2. added
    API changeChanges to existing functions or objects in the API.
    on May 29, 2025
  3. kgryte commented on May 29, 2025

    @kgryte
    Contributor

    I think that the definition of copy=False is unclear when two dtypes only differ in signedness

    I'd argue that the spec is not actually unclear here. If the specified dtype and the dtype of the array differ, then a newly allocated array must be returned.

    I think what you want is what is suggested in #266, which is the ability to explicitly return a new view.

    Given that NumPy is not going to change (ref numpy/numpy#27509), I don't think there is much we can do here in terms of changing astype. Instead, I suggest pushing for an explicit reinterpretation API; however, this will be a bit more involved, as it will require broader ecosystem alignment.

    As such, I'll go ahead and close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    API changeChanges to existing functions or objects in the API.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions