pretty printing graphs
Bengt Richter
bokr at oz.net
Tue Jul 29 00:27:21 EDT 2003
On 28 Jul 2003 16:30:03 -0700, mis6 at pitt.edu (Michele Simionato) wrote:
>"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!
>
Decided to try the tree print I did for John Hunter in pphunter.py on your class tree:
explore is just a quick-n-dirty to make the tree.
====< mrog.py >=====================
# 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
import pphunter
def explore(cls, tree):
node = pphunter.Node(pphunter.TextBox(cls.__name__))
tree.children.append(node)
for b in cls.__bases__: explore(b, node)
root = pphunter.Node(pphunter.TextBox('root'))
explore(A, root)
print root.children[0].showInPage(20, 60)
====================================
Result:
[21:26] C:\pywk\clp>python mrog.py
+-+
|A|
+-+
+-+ +-+
|B| |C|
+-+ +-+
+-+ +-+ +-+ +-+ +-+
|E| |D| |F| |D| |G|
+-+ +-+ +-+ +-+ +-+
+------+ +------+ +------+ +------+ +------+
|object| |object| |object| |object| |object|
+------+ +------+ +------+ +------+ +------+
I guess I will have to do connector lines ;-)
BTW, I found a bug in the showInPage method of pphunter.Node. It should be
--
def showInPage(self, pageHeight=6*11, pageWidth=78):
return '\n'.join(self.boxlines(pageHeight, pageWidth))
--
(I capitalized pageHeight and page Width) . Boo :-(
(see 'pretty printing graphs' thread).
Regards,
Bengt Richter
More information about the Python-list
mailing list