From b84692c9a8fb511d65869490726eff13619c477d Mon Sep 17 00:00:00 2001
From: Olivier BICHLER <olivier.bichler@cea.fr>
Date: Fri, 27 Sep 2024 11:29:20 +0200
Subject: [PATCH] Fixed possible segfault at exist

---
 include/aidge/utils/DynamicAttributes.hpp | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)

diff --git a/include/aidge/utils/DynamicAttributes.hpp b/include/aidge/utils/DynamicAttributes.hpp
index 26cc6111d..6c6f3b8d9 100644
--- a/include/aidge/utils/DynamicAttributes.hpp
+++ b/include/aidge/utils/DynamicAttributes.hpp
@@ -277,7 +277,21 @@ public:
         return mAttrs;
     }
 
-    virtual ~DynamicAttributes() {}
+    virtual ~DynamicAttributes() {
+#ifdef PYBIND
+        if (!Py_IsInitialized()) {
+            // Resets the internal pointer of py::object to nullptr without decreasing the object's reference count.
+            // At this point, the Python interpreter may have exited (it is the case if the current DynamicAttribute being destroyed is static),
+            // in which case py:object has already being destroyed despite the reference counting being > 0.
+            // See https://github.com/pybind/pybind11/issues/1598
+            for (auto& attr : mAttrs) {
+                if (attr.second.type() == typeid(py::object)) {
+                    future_std::any_cast<py::object&>(attr.second).release();
+                }
+            }
+        }
+#endif
+    }
 
     friend bool operator<(const DynamicAttributes& lhs, const DynamicAttributes& rhs);
     friend struct std::hash<DynamicAttributes>;
-- 
GitLab