From 87f8c92399f7ac5d5089063ec760b7c703570c85 Mon Sep 17 00:00:00 2001
From: Justin Carpentier <justin.carpentier@inria.fr>
Date: Fri, 21 Feb 2020 09:28:27 +0100
Subject: [PATCH] core: use singleton strategy to load numpy_array module

---
 include/eigenpy/details.hpp    |  1 -
 include/eigenpy/numpy-type.hpp | 42 +++++++++++++++++++++++++++++++++-
 2 files changed, 41 insertions(+), 2 deletions(-)

diff --git a/include/eigenpy/details.hpp b/include/eigenpy/details.hpp
index 22110af0..33501dbd 100644
--- a/include/eigenpy/details.hpp
+++ b/include/eigenpy/details.hpp
@@ -573,7 +573,6 @@ namespace eigenpy
   };
 #endif
 
-#define numpy_import_array() {if (_import_array() < 0) {PyErr_Print(); PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); } }
   
   template<typename MatType,typename EigenEquivalentType>
   EIGENPY_DEPRECATED
diff --git a/include/eigenpy/numpy-type.hpp b/include/eigenpy/numpy-type.hpp
index 07be4c99..557276b7 100644
--- a/include/eigenpy/numpy-type.hpp
+++ b/include/eigenpy/numpy-type.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright 2018-2020, INRIA
+ * Copyright 2018-2020 INRIA
 */
 
 #ifndef __eigenpy_numpy_type_hpp__
@@ -102,9 +102,11 @@ namespace eigenpy
     }
 
   protected:
+    
     NumpyType()
     {
       pyModule = bp::import("numpy");
+      
 #if PY_MAJOR_VERSION >= 3
       // TODO I don't know why this Py_INCREF is necessary.
       // Without it, the destructor of NumpyType SEGV sometimes.
@@ -132,7 +134,45 @@ namespace eigenpy
 
     NP_TYPE np_type;
   };
+
+  namespace details
+  {
+    struct import_numpy
+    {
     
+      static bool status()
+      {
+        return instance().imported;
+      }
+      
+    protected:
+      
+      static import_numpy & instance()
+      {
+        static import_numpy m_instance;
+        return m_instance;
+      }
+      
+      import_numpy()
+      : imported(false)
+      {
+        if(_import_array() < 0)
+        {
+          PyErr_Print();
+          PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import");
+        }
+        else
+          imported = true;
+      }
+      
+      bool imported;
+    };
+  } //  namespace details
+    
+  inline bool numpy_import_array()
+  {
+    return details::import_numpy::status();
+  }
 }
 
 #endif // ifndef __eigenpy_numpy_type_hpp__
-- 
GitLab