James Mills  committed ac2574f

- Added a new helper function ``tryimport`` which given a
list of modules to try and import and an optional message; will try to
import each module returning the first successful one. If none of the
modules can be improted, a warning is useed with the optional message.

  • Participants
  • Parent commits ec43774
  • Branches default

Comments (0)

Files changed (1)

File circuits/tools/

 from hashlib import md5
+from warnings import warn
-    import pydot
-    HAS_PYDOT = True
-except ImportError:
-    HAS_PYDOT = False
+def tryimport(modules, message=None):
+    for module in modules:
+        try:
+            return __import__(module, globals(), locals())
+        except ImportError:
+            pass
+    if message:
+        warn(message)
 def walk(x, f, d=0, v=None):
     if not v:
             for r in walk(c, f, d + 1, v):
                 yield r
 def edges(x, e=None, v=None):
     if not e:
         e = set()
         edges(c, e, v)
     return e
 def findroot(x):
     if x.manager == x:
         return x
         return findroot(x.manager)
 def kill(x):
     for c in x.components.copy():
     if x.manager != x:
 def graph(x, name=None):
     """Display a directed graph of the Component structure of x
     def getname(c):
         return "%s-%s" % (, md5(str(hash(c))).hexdigest()[-4:])
-    if HAS_PYDOT:
+    pydot = tryimport(("pydot",))
+    if pydot is not None:
         graph_edges = []
         for (u, v) in edges(x):
             graph_edges.append(("\"%s\"" % getname(u), "\"%s\"" % getname(v)))
         return "%s* %s" % (" " * d, x)
     return "\n".join(walk(x, printer))
 def reprhandler(c, h):
     """Display a nicely formatted Event Handler, h from Component c.
     p = attrs["priority"]
     return format % (f, channels, t, p)
 def inspect(x):
     """Display an inspection report of the Component or Manager x