From 6aa3b335f4205c7c7efd9faeb1f39adfcf0f1389 Mon Sep 17 00:00:00 2001 From: gentlegiantJGC Date: Wed, 14 May 2025 15:41:08 +0100 Subject: [PATCH] fix(types): Buffer type hint (#5662) * Fix Buffer type hint collections.abc.Buffer was added in Python 3.12. The previous behaviour should be used prior to this version. * Fix comment * Fix indentation * style: pre-commit fixes * Fix test * Add missing import * style: pre-commit fixes --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- include/pybind11/cast.h | 2 +- include/pybind11/detail/common.h | 7 +++++++ tests/test_buffers.py | 10 ++++++---- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/include/pybind11/cast.h b/include/pybind11/cast.h index 3bedb9d1a..44f8e1f83 100644 --- a/include/pybind11/cast.h +++ b/include/pybind11/cast.h @@ -1387,7 +1387,7 @@ struct handle_type_name { }; template <> struct handle_type_name { - static constexpr auto name = const_name("collections.abc.Buffer"); + static constexpr auto name = const_name(PYBIND11_BUFFER_TYPE_HINT); }; template <> struct handle_type_name { diff --git a/include/pybind11/detail/common.h b/include/pybind11/detail/common.h index e9d954bc4..e3df32df3 100644 --- a/include/pybind11/detail/common.h +++ b/include/pybind11/detail/common.h @@ -239,6 +239,13 @@ # define PYBIND11_SUBINTERPRETER_SUPPORT #endif +// 3.12 Compatibility +#if 0x030C0000 <= PY_VERSION_HEX +# define PYBIND11_BUFFER_TYPE_HINT "collections.abc.Buffer" +#else +# define PYBIND11_BUFFER_TYPE_HINT "typing_extensions.Buffer" +#endif + // #define PYBIND11_STR_LEGACY_PERMISSIVE // If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject // (probably surprising and never documented, but this was the diff --git a/tests/test_buffers.py b/tests/test_buffers.py index d335b71e9..a712f2bda 100644 --- a/tests/test_buffers.py +++ b/tests/test_buffers.py @@ -3,6 +3,7 @@ from __future__ import annotations import ctypes import io import struct +import sys import pytest @@ -228,10 +229,11 @@ def test_ctypes_from_buffer(): def test_buffer_docstring(): - assert ( - m.get_buffer_info.__doc__.strip() - == "get_buffer_info(arg0: collections.abc.Buffer) -> pybind11_tests.buffers.buffer_info" - ) + if sys.version_info >= (3, 12): + docstring = "get_buffer_info(arg0: collections.abc.Buffer) -> pybind11_tests.buffers.buffer_info" + else: + docstring = "get_buffer_info(arg0: typing_extensions.Buffer) -> pybind11_tests.buffers.buffer_info" + assert m.get_buffer_info.__doc__.strip() == docstring def test_buffer_exception():