From 7f7b70b943b5003230babf9495d956c27992cd09 Mon Sep 17 00:00:00 2001 From: Michael Carlstrom Date: Thu, 19 Dec 2024 12:57:37 -0800 Subject: [PATCH] add handle support to attr_with_type_hint --- include/pybind11/cast.h | 16 ++++++++++++++++ include/pybind11/pytypes.h | 3 +++ tests/test_pytypes.py | 1 - 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/include/pybind11/cast.h b/include/pybind11/cast.h index 952bda090..6ef405f1e 100644 --- a/include/pybind11/cast.h +++ b/include/pybind11/cast.h @@ -1368,6 +1368,22 @@ object object_or_cast(T &&o) { // Declared in pytypes.h: // Written here so make_caster can be used +template +template +obj_attr_accessor object_api::attr_with_type_hint(handle key) const { +#if !defined(__cpp_inline_variables) + static_assert(!std::is_same::value, + "C++17 feature __cpp_inline_variables not available: " + "https://en.cppreference.com/w/cpp/language/static#Static_data_members"); +#endif + object ann = annotations(); + if (ann.contains(key)) { + throw std::runtime_error("__annotations__[\"" + std::string(key) + "\"] was set already."); + } + ann[key] = make_caster::name.text; + return {derived(), reinterpret_borrow(key)}; +} + template template str_attr_accessor object_api::attr_with_type_hint(const char *key) const { diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index a30ecf4b8..d8d158b95 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -114,6 +114,9 @@ public: str_attr_accessor attr(const char *key) const; // attr_with_type_hint is implemented in cast.h: + template + obj_attr_accessor attr_with_type_hint(handle key) const; + template str_attr_accessor attr_with_type_hint(const char *key) const; diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index 9303b9401..c0d1598fa 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -1160,7 +1160,6 @@ def test_class_attribute_types() -> None: def test_redeclaration_attr_with_type_hint() -> None: obj = m.Instance() m.attr_with_type_hint_float_x(obj) - help(obj) assert get_annotations_helper(obj)["x"] == "float" with pytest.raises( RuntimeError, match=r'^__annotations__\["x"\] was set already\.$'