Is it OK to subclass memoryview?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
cdwilson
Posts: 11
Joined: Thu Jul 18, 2019 3:54 am
Location: Castro Valley, CA, USA

Is it OK to subclass memoryview?

Post by cdwilson » Sat Sep 21, 2019 2:04 am

CPython doesn't allow subclassing memoryview:

Code: Select all

>>> class MyMV(memoryview):
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'memoryview' is not an acceptable base type
but MicroPython does:

Code: Select all

>>> class MyMV(memoryview):
...     pass
>>>
I'm curious if anybody knows:
1. The reason why this was allowed in MicroPython but not in CPython? (I'm actually not sure why this is disallowed in CPython)
2. Are there any "gotchas" or things to be aware of when subclassing memoryview in MicroPython?

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Is it OK to subclass memoryview?

Post by pythoncoder » Sat Sep 21, 2019 6:57 am

In general MicroPython doesn't support subclassing built-in types and doing so will produce unpredictable results. The one exception I'm aware of is framebuf which is specifically designed to be subclassed. See https://github.com/micropython/micropyt ... ifferences.
Peter Hinch
Index to my micropython libraries.

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Is it OK to subclass memoryview?

Post by jimmo » Sun Sep 22, 2019 5:11 am

cdwilson wrote:
Sat Sep 21, 2019 2:04 am
1. The reason why this was allowed in MicroPython but not in CPython? (I'm actually not sure why this is disallowed in CPython)
The simple answer would be that it's extra code to check this case. It also might just be an oversight.
cdwilson wrote:
Sat Sep 21, 2019 2:04 am
2. Are there any "gotchas" or things to be aware of when subclassing memoryview in MicroPython?
Like Peter said, support for subclassing built-ins is a bit unpredictable. One of the main contributors to this is that the implementations of the built-in classes assume they _aren't_ subclassed, so they don't do things like use the MRO to look up methods, or check types using the class hierarchy etc. (This mostly saves on code size).

One example for memoryview that might be surprising:

Code: Select all

class foo(memoryview):
  def get_section(self):
    return self[4:6]

b = b'abcdefghi'
f = foo(b)
f.get_section() --> this returns a memoryview, not a foo
That might actually be what you want, in that example :)

Post Reply