Skip to content

Instantly share code, notes, and snippets.

@rodrigorgs
Last active March 29, 2025 10:57
Show Gist options
  • Select an option

  • Save rodrigorgs/b091defd1c5974ea33a425bb5ee23de3 to your computer and use it in GitHub Desktop.

Select an option

Save rodrigorgs/b091defd1c5974ea33a425bb5ee23de3 to your computer and use it in GitHub Desktop.
Visualize classes and objects
from graphviz import Digraph
def visualize_relationships(objects=None):
'''
Visualize, as a directed graph, the relationships between objects.
:param objects: A list of objects to visualize. If None, all objects in the current module will be visualized.
'''
if objects is None:
objects = [obj for obj in globals().values() if isinstance(obj, tuple(cls for cls in globals().values() if isinstance(cls, type) and cls.__module__ == '__main__'))]
dot = Digraph()
for obj in objects:
obj_name = next((name for name, value in globals().items() if value is obj), None)
attributes = "\n".join(
f"{k}: {v}" for k, v in obj.__dict__.items() if not any(isinstance(v, type(o)) for o in objects)
)
label = f"{obj_name}: {obj.__class__.__name__}\n---\n{attributes}" if obj_name else f"{obj.__class__.__name__}\n---\n{attributes}"
dot.node(str(id(obj)), label, shape='rectangle')
for attr_name, attr_value in obj.__dict__.items():
if any(isinstance(attr_value, type(o)) for o in objects):
dot.edge(str(id(obj)), str(id(attr_value)), label=attr_name)
return dot
# In Jupyter Notebook, you can use the following code to display the graph:
visualize_relationships()
# -----------------
import dis
def visualize_class(cls):
dot = Digraph()
attributes = get_class_attributes(cls)
methods = [f"{name}()" for name, value in cls.__dict__.items() if callable(value) and not name.startswith('__')]
label = f"""<
<table border="0" cellborder="1" cellspacing="0" cellpadding="4">
<tr> <td> <b>{cls.__name__}</b> </td> </tr>
<tr><td>
<table border="0" cellborder="0" cellspacing="0" >
{' '.join([f'<tr> <td align="left" >+ {attr}</td> </tr>' for attr in attributes])}
</table>
</td></tr>
<tr><td>
<table border="0" cellborder="0" cellspacing="0" >
{' '.join([f'<tr> <td align="left" >+ {attr}</td> </tr>' for attr in methods])}
</table>
</td></tr>
</table>
>"""
dot.node(cls.__name__, label, shape='plaintext')
return dot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment