pretty printing graphs
Michele Simionato
mis6 at pitt.edu
Mon Jul 28 19:30:03 EDT 2003
"Scherer, Bill" <Bill.Scherer at verizonwireless.com> wrote in message news:<mailman.1059413382.3564.python-list at python.org>...
Hey "dot" is great! I didn't know about it before readin your post.
In a very short time I came out with the following recipe to draw
Python inheritance hierarchies (which I post since it is pretty
short and useful ;):
"How to draw inheritance hierarchies via dot"
import os
def label(i,n):
if n>1: return '[label="%s"]' % (i+1)
return ""
def dotMRO(cls):
"Generates the dot code for the MRO directed graph"
yield "digraph MRO_of_%s{\n" % cls.__name__
for c in cls.__mro__:
n=len(c.__bases__)
yield ' '.join([' %s -> %s %s;' % (b.__name__,c.__name__,label(i,n))
for i,b in enumerate(c.__bases__)])
yield '}'
# Example hierarchy
O = object
class F(O): pass
class E(O): pass
class D(O): pass
class G(O): pass
class C(F,D,G): pass
class B(E,D): pass
class A(B,C): pass
# creates the graph
dotcode='\n'.join(dotMRO(A)); print dotcode
os.system('echo "%s" | dot -Tps > prova.ps' % dotcode)
os.system('gv prova.ps&')
Assuming you have "dot" and the standard Unix tools installed this
will generate a very nice diagram. I am open to suggestion to improve it,
since this is may first trial with "dot". I am quite impressed by the
easy of use.
Very nice!
Michele
More information about the Python-list
mailing list