Skip to content

MAINT: Avoid a redundant copy on a[...] = b#28163

Merged
charris merged 1 commit intonumpy:mainfrom
mtsokol:assign-no-copy
Jan 16, 2025
Merged

MAINT: Avoid a redundant copy on a[...] = b#28163
charris merged 1 commit intonumpy:mainfrom
mtsokol:assign-no-copy

Conversation

@mtsokol
Copy link
Member

@mtsokol mtsokol commented Jan 16, 2025

Fixes #28070

In the example presented in #28070 there's an unnecessary copy made by calling __array__ with copy=True:

import numpy as np

class MyThing(object):
    def __array__(self, dtype=None, copy=None):
        print(f"MyThing.__array__(dtype={dtype}, copy={copy})")
        return np.ones((5, 5))

u = np.zeros((5, 5))
v = MyThing()

u[...] = v

I think we can switch from "always copy" to "copy if needed" for the input shape&dtype discovery in the PyArray_CopyObject function.
I want to stress that the src to dest copy is done anyway (AFAIU indexed assignment can't return a view) as PyArray_CopyObject calls PyArray_AssignArray(dest, src, ...) which iterates over elements and copies them to dest.

@mtsokol mtsokol self-assigned this Jan 16, 2025
@charris charris changed the title Avoid a redundant copy on a[...] = b MAINT: Avoid a redundant copy on a[...] = b Jan 16, 2025
Copy link
Contributor

@mhvk mhvk left a comment

Choose a reason for hiding this comment

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

Looks good, thanks!

@charris charris merged commit 441d1da into numpy:main Jan 16, 2025
68 checks passed
@mtsokol mtsokol deleted the assign-no-copy branch January 16, 2025 18:34
@charris
Copy link
Member

charris commented Jan 16, 2025

Thanks Mateusz.

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.

BUG: unnecessary copy on assignment

3 participants