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>
This commit is contained in:
gentlegiantJGC
2025-05-14 15:41:08 +01:00
committed by GitHub
parent 95e8f89be1
commit 6aa3b335f4
3 changed files with 14 additions and 5 deletions

View File

@@ -1387,7 +1387,7 @@ struct handle_type_name<bytes> {
};
template <>
struct handle_type_name<buffer> {
static constexpr auto name = const_name("collections.abc.Buffer");
static constexpr auto name = const_name(PYBIND11_BUFFER_TYPE_HINT);
};
template <>
struct handle_type_name<int_> {

View File

@@ -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

View File

@@ -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():