Synthesize __buffer__ for C types supporting buffer protocol (Python 3.12+)

When running on Python 3.12+, probe classes with memoryview() and add
__buffer__(flags: int, /) -> memoryview if the buffer protocol is supported.
This enables type-safe memoryview() calls on mathutils types in Blender 5.1+.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph HENRY 2026-03-27 15:25:27 +01:00
parent 8879d14073
commit a523a9fcb7

View File

@ -1498,6 +1498,31 @@ def introspect_class(cls: type[object], module_name: str) -> StructData:
} }
) )
# Synthesize __buffer__ for classes supporting the C buffer protocol.
# Only available in Python 3.12+ (PEP 688).
if sys.version_info >= (3, 12) and "__buffer__" not in method_names:
try:
instance = cls()
memoryview(instance)
methods.append(
{
"name": "__buffer__",
"doc": "",
"params": [
{
"name": "flags",
"type": "int",
"default": None,
"kind": "POSITIONAL_ONLY",
}
],
"return_type": "memoryview",
"is_classmethod": False,
}
)
except Exception:
pass
return { return {
"name": cls.__name__, "name": cls.__name__,
"doc": class_doc, "doc": class_doc,