From 8da0ce0350fbbfc261303c9eb7413336e269f121 Mon Sep 17 00:00:00 2001 From: Michael Carlstrom Date: Thu, 5 Dec 2024 19:40:10 -0500 Subject: [PATCH] add #if 3.9 --- include/pybind11/pytypes.h | 16 +++++++++++----- tests/test_pytypes.py | 8 +++++--- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index 7fed214d4..7d8e13756 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -2569,12 +2569,18 @@ template // Always a dict // https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older object object_api::annotations() const { - if (isinstance(derived())){ - return getattr(getattr(derived(), "__dict__"), "__annotations__", dict()); - } - else{ + // Python 3.8, 3.9 + #if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION <= 9 + if (isinstance(derived())){ + return getattr(derived(), "__dict__").get("__annotations__", dict()); + } + else{ + return getattr(derived(), "__annotations__", dict()); + } + // Python 3.10+ + #else return getattr(derived(), "__annotations__", dict()); - } + #endif } template diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index 40cba7c8e..c59a094a7 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -1102,10 +1102,12 @@ def test_dict_ranges(tested_dict, expected): assert m.dict_iterator_default_initialization() assert m.transform_dict_plus_one(tested_dict) == expected - +# https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older def get_annotations_helper(o): - print(help(o)) - return getattr(o, "__annotations__", None) + if isinstance(o, type): + return o.__dict__.get('__annotations__', {}) + else: + return getattr(o, '__annotations__', {}) def test_module_attribute_types() -> None: