How to make a custom python class to support memoryview conversion

87
April 12, 2022, at 10:00 AM

Is it possible for a custom class to implement memoryview(obj)?

For example,

class A:
    def __init__(self):
        self.b = b'sdfajsdfjkasdf'
    def __memoryview__(self):
        return self.b

so that

a = A()
mv = memoryview(a) # returns the memoryview of a.b

is a valid operation.

Answer 1

Not possible. memoryview only accepts arguments that support the buffer protocol, and the buffer protocol is C-only. There are no Python-level hooks.

I don't know of any explicit statement regarding this in the docs, but all the buffer protocol documentation is C-only, and if you're comfortable with C, you can check the type object implementation and see that nothing ever sets bf_getbuffer or bf_releasebuffer to any sort of wrapper around a Python-level hook.

You can define a class that subclasses an existing class with buffer support, but that will make your objects actually be instances of that existing class. For example, if you make your class a subclass of bytes, then memoryview(a) will create a memoryview over your object. It will not create a memoryview of a.b, and there will be all sorts of usually-undesirable side effects. Do not do this just to provide memoryview support; use memoryview(a.b).

Rent Charter Buses Company
READ ALSO
Using pd.read_html to return a specific table from a webpage of multiple tables

Using pd.read_html to return a specific table from a webpage of multiple tables

I am trying to return a specific table from this webpage

67
Django - get data from form and return to user so they can edit/delete

Django - get data from form and return to user so they can edit/delete

New to Django and making a restuarant booking systemI have everything going to my database but now i'm trying to return the info back to the user, ideally in a similar form view to what i have, so they can edit or delete the booking

78
For python's built-in sort()'s key parameter, when to use base class vs object as identifier?

For python's built-in sort()'s key parameter, when to use base class vs object as identifier?

Let me take an example to clarify what I am talking aboutSay I'm trying to sort() a string s with a key of count (frequency of letters) and in a different case, with a key of lower

86
Get cpu temperature from python? (windows)

Get cpu temperature from python? (windows)

PleaseI have tried every google search result and none of them worked

127