mgedmin / objgraph

Visually explore Python object graphs
http://mg.pov.lt/objgraph/
MIT License
753 stars 72 forks source link

Allow saving graph dot to in memory string instead of file #21

Closed jwmullally closed 9 years ago

jwmullally commented 9 years ago

Would it be possible to support outputting the generated graph dot text to file objects also?

This would allow rendering in IPython notebooks without needing to write and track temporary files by e.g. writing to a StringIO object.

(Internally pygraphviz handles all this with STDIN/STDOUT)

Currently you need to do this (which admittedly isn't too bad...):

import pygraphviz
import IPython.display
import objgraph

x = [[1,2,3], 4,5,6]
objgraph.show_refs(x, filename='temp.dot')
IPython.display.Image(pygraphviz.AGraph(filename='temp.dot').draw(format='png', prog='dot'))

Rendering to a PNG file below is shorter, but I think the dot example above demonstrates the general purpose usefulness of being able to capture that version of the graph.

import pygraphviz
import IPython.display
import objgraph

x = [[1,2,3], 4,5,6]
objgraph.show_refs(x, filename='temp.png')
IPython.display.Image('temp.png')
mgedmin commented 9 years ago

This is such a good idea that it was in fact implemented in objgraph 2.0.0: "show_ref and show_backref now accept a file-like object as an alternative to a filename" ;-)

It uses a different argument objgraph.show_refs(x, output=StringIO()) because ... actually I don't know why. The person who submitted the PR had it that way.

(I see that the changelog entry can be misread to assume that you can pass a file-like object to the filename argument. I'll fix the changelog.)