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

1

7

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
Gid answered 1/3, 2019 at 12:44 Comment(0)
G
9

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).

Geometrician answered 1/3, 2019 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.