James Mills avatar James Mills committed ac2574f

- circuits.tools: 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.

Comments (0)

Files changed (1)


 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" % (c.name, 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
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.