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

In-place arithmetic operators of memoryviews behave differently from those of ndarrays #3403

Open
grothesque opened this issue Mar 9, 2020 · 0 comments

Comments

@grothesque
Copy link
Contributor

@grothesque grothesque commented Mar 9, 2020

With Cython 29.2 (from Debian stable) the statement

a += b

where a is a Cython memory view is equivalent to

a = a + b

i.e. a new object is created and assigned to the name a. This is different from how augmented arithmetic operations work for Numpy arrays (where the first form modifies a in place) and also IMHO from what one would expect. Is this perhaps because in-place operators are not defined for memoryviews and Python thus falls back to normal operators?

If this behavior is by design, I believe it should be documented (I could not find anything).

The following script demonstrates the issue. Note that replacing a += ... by a[:] += ... is a work-around for the issue.

# Compile with
# cython3 --embed bug.pyx && gcc bug.c -I /usr/include/python3.7/ -lpython3.7m

import numpy as np


def memoryview():
    cdef double[:] tmp = np.zeros(10)
    return tmp


def ndarray():
    tmp = np.zeros(10)
    return tmp


def main(f):
    a = f()
    print(type(a))
    print(id(a))
    a += np.arange(len(a))
    print(id(a))


if __name__ == "__main__":
    main(memoryview)
    main(ndarray)

I get the following output

<class 'bug._memoryviewslice'>
140199050152928
140199050328384
<class 'numpy.ndarray'>
140199073013152
140199073013152
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
1 participant
You can’t perform that action at this time.