[dataio] Avoid many imports of the same module (SPARQLWrapper and JSON)
authorSimon Chabot <simon.chabot@logilab.fr>
Tue, 27 Nov 2012 20:17:49 +0100
changeset 170 3679c8eab2be
parent 169 2ca1f2b23577
child 171 87249081b27d
[dataio] Avoid many imports of the same module (SPARQLWrapper and JSON) The ImportError is still raised in case of failure but only when the ``sparqlquery`` function is called, but there are no more imports made each time the function is called.
dataio.py
--- a/dataio.py	Thu Nov 29 14:11:20 2012 +0100
+++ b/dataio.py	Tue Nov 27 20:17:49 2012 +0100
@@ -19,6 +19,12 @@
 
 import csv
 
+try:
+    from SPARQLWrapper import SPARQLWrapper, JSON
+    SPARQL_ENABLED = True
+except ImportError:
+    SPARQL_ENABLED = False
+
 
 def autocasted(data, encoding=None):
     """ Try to convert data into a specific type
@@ -39,7 +45,9 @@
     """ Run the sparql query on the given endpoint, and wrap the items in the
     indexes form. If indexes is empty, keep raw output"""
 
-    from SPARQLWrapper import SPARQLWrapper, JSON
+    if not SPARQL_ENABLED:
+        raise ImportError("You have to install SPARQLWrapper and JSON modules to"
+                          "used this function")
 
     sparql = SPARQLWrapper(endpoint)
     sparql.setQuery(query)