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
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With