← index #6523Issue #7718
Related · high · value 1.698
QUERY · ISSUE

Taking slice of memoryview in Viper function crashes PyBoard

openby twisteroidambassadoropened 2020-10-07updated 2025-07-02
bugpy-core

On a PyBoard v1.1 with firmware 1.13, put the following code into a file:

import micropython


@micropython.viper
def take_memoryview_slice():
    ba = bytearray(10)
    mv = memoryview(ba)
    slice = mv[0:1]

Running take_memoryview_slice() resets the PyBoard.

CANDIDATE · ISSUE

Slice operation on memoryview causes allocation

closedby peterhinchopened 2021-08-27updated 2021-08-27

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)

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied