Skip to content

fix(types): Buffer type hint #5662

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion include/pybind11/cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -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_> {
Expand Down
7 changes: 7 additions & 0 deletions include/pybind11/detail/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 6 additions & 4 deletions tests/test_buffers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import ctypes
import io
import struct
import sys

import pytest

Expand Down Expand Up @@ -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():
Expand Down
Loading