diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index d7482927b..feb18ac63 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -2571,11 +2571,10 @@ template object object_api::annotations() const { // Python 3.8, 3.9 #if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION <= 9 - if (hasattr(derived(), "__dict__")) { - return getattr(getattr(derived(), "__dict__"), "__annotations__", dict()); - } else { - return getattr(derived(), "__annotations__", dict()); + if (!hasattr(derived(), "__annotations__")) { + setattr(derived(), "__annotations__", dict()); } + return attr("__annotations__"); // Python 3.10+ #else return getattr(derived(), "__annotations__", dict()); diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index 332f2125e..44f161a14 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -1125,7 +1125,6 @@ def test_class_attribute_types() -> None: assert empty_annotations == {} assert annotations["x"] == "float" assert annotations["dict_str_int"] == "dict[str, int]" - assert False def test_final_annotation() -> None: