Skip to content

Commit 6aa3b33

Browse files
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>
1 parent 95e8f89 commit 6aa3b33

File tree

3 files changed

+14
-5
lines changed

3 files changed

+14
-5
lines changed

include/pybind11/cast.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -1387,7 +1387,7 @@ struct handle_type_name<bytes> {
13871387
};
13881388
template <>
13891389
struct handle_type_name<buffer> {
1390-
static constexpr auto name = const_name("collections.abc.Buffer");
1390+
static constexpr auto name = const_name(PYBIND11_BUFFER_TYPE_HINT);
13911391
};
13921392
template <>
13931393
struct handle_type_name<int_> {

include/pybind11/detail/common.h

+7
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,13 @@
239239
# define PYBIND11_SUBINTERPRETER_SUPPORT
240240
#endif
241241

242+
// 3.12 Compatibility
243+
#if 0x030C0000 <= PY_VERSION_HEX
244+
# define PYBIND11_BUFFER_TYPE_HINT "collections.abc.Buffer"
245+
#else
246+
# define PYBIND11_BUFFER_TYPE_HINT "typing_extensions.Buffer"
247+
#endif
248+
242249
// #define PYBIND11_STR_LEGACY_PERMISSIVE
243250
// If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
244251
// (probably surprising and never documented, but this was the

tests/test_buffers.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import ctypes
44
import io
55
import struct
6+
import sys
67

78
import pytest
89

@@ -228,10 +229,11 @@ def test_ctypes_from_buffer():
228229

229230

230231
def test_buffer_docstring():
231-
assert (
232-
m.get_buffer_info.__doc__.strip()
233-
== "get_buffer_info(arg0: collections.abc.Buffer) -> pybind11_tests.buffers.buffer_info"
234-
)
232+
if sys.version_info >= (3, 12):
233+
docstring = "get_buffer_info(arg0: collections.abc.Buffer) -> pybind11_tests.buffers.buffer_info"
234+
else:
235+
docstring = "get_buffer_info(arg0: typing_extensions.Buffer) -> pybind11_tests.buffers.buffer_info"
236+
assert m.get_buffer_info.__doc__.strip() == docstring
235237

236238

237239
def test_buffer_exception():

0 commit comments

Comments
 (0)