Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to print a class' hierarchy in tree form?

Is there a function that can print a python class' heirarchy in tree form, like git log --graph does for git commits?

Example of what I'd like to do:

class A(object): pass
class B(A): pass
class C(B): pass
class D(A): pass
class E(C, D): pass

printtree(E)

Example of what the output might look like (but variations are fine). Bonus points if the mro can also be read off directly from the graph, as I've done here from top to bottom, but if not that's fine as well.

E
|\
C |
| D
B |
|/
A
|
object
like image 700
Heshy Avatar asked Mar 01 '19 12:03

Heshy


Video Answer


1 Answers

No, there is no built-in function to do this, you'd have to build your own. But know that laying out and drawing ASCII graphs is a complicated task, the Mercurial graphing code (a Python equivalent of git log --graph) is quite involved and complicated.

It'd be much more productive to leave graph layouts to a dedicated utility like Graphviz. Someone has already written the code to do this, see this article by Michele Simionato, Ph. D, where they turn:

class M(type): pass # metaclass
class F(object): pass
class E(object): pass
class D(object): pass
class G(object): __metaclass__=M
class C(F,D,G): pass
class B(E,D): pass
class A(B,C): pass

into

enter image description here

complete with the full MRO outlined in a label. While the code was written over 15 years ago, it still works, as designed, on Python 3 (I tested with 3.8.0a1).

like image 96
Martijn Pieters Avatar answered Sep 21 '22 22:09

Martijn Pieters