Special Method Protocols

__buffer__() — buffer protocol

Expose storage through Python-level buffer protocol (3.12+). Return a memoryview satisfying the requested flags; reject unsupported layouts or permissions. This example delegates the request to a bytearray exporter.

Formal Syntax & Structure

python syntaxpython
def __buffer__(self, flags):

Parameters & Attributes

NameTypeDescription
flagsintRequested buffer capabilities.

Return Value

memoryview

Requested buffer view.

Working Example

Example Snippetpython
class Packet:    def __init__(self): self.data=bytearray(b"AB")    def __buffer__(self, flags): return self.data.__buffer__(flags)def demo():    p=Packet()    with memoryview(p) as view:        view[0]=90    return bytes(p.data)print(demo())
Python Reference