Home > Software design >  How to make a custom python class to support memoryview conversion
How to make a custom python class to support memoryview conversion

Time:02-08

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.

CodePudding user response:

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).

CodePudding user response:

How about implementing the __bytes__ method that returns a bytes string of the class data. Then you could use memoryview(bytes(a)).

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

a = A()
memoryview(bytes(a))
  •  Tags:  
  • Related