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

Slice operation on memoryview causes allocation #7718

Closed
peterhinch opened this issue Aug 27, 2021 · 2 comments
Closed

Slice operation on memoryview causes allocation #7718

peterhinch opened this issue Aug 27, 2021 · 2 comments

Comments

@peterhinch
Copy link
Contributor

The docs lead one to believe that slicing a memoryview should be allocation free, but this seems not to be the case.

This arose in this forum thread. The user has a timer ISR which uses SPI to read first the number of bytes to read, followed by a subsequent SPI read of the payload. I suggested a memoryview, but this does not work as the slice operation causes an allocation.

I replicated the issue with this sample which can be pasted to a Pyboard:

from machine import SPI
from pyb import Timer
import micropython
import time
micropython.alloc_emergency_exception_buf(100)

s = SPI(1)
buf = bytearray(20)
mv = memoryview(buf)
tim = Timer(1)

def cb(t):
    #s.readinto(mv)  # Works
    s.readinto(mv[:5])  # Memory error

tim.init(freq=10, callback=cb)
while True:
    print(buf)
    time.sleep(1)
@jimmo
Copy link
Member

jimmo commented Aug 27, 2021

The docs lead one to believe...

I'm guessing it's this line that probably gives this impression.

func(mv[30:2000]) # a pointer to memory is passed

I think it's worth updating the docs to clarify that slicing a memoryview creates a new memoryview (as well as requiring a heap allocation for the slice) (ref #4244 for more details).

Not sure what the solution to the underlying issue is as it will likely require extending the memoryview API (e.g. to add a way to adjust an existing memoryview as discussed in #4244 and elsewhere) but this will break CPython compatibility... perhaps we need to raise this with python-dev.

@peterhinch
Copy link
Contributor Author

Apologies - my memory is quite hopeless these days.

In penance I will raise a docs PR :)

tannewt added a commit to tannewt/circuitpython that referenced this issue Oct 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants